As a scripting language, JavaScript can bind events to elements on the page, so that when a specified event occurs, the corresponding event handler can be automatically called to handle the event. So how to add events to elements? The following article will introduce to you three ways to bind events in JS. I hope it will be helpful to you!
In order for the browser to automatically call the corresponding event handler to handle the event when an event occurs, it is necessary to bind an event handler to the event source (the binding event handler also called the registered event handler).
There are three ways to bind event handlers:
In HTML tags, use event attributes (such as onclick) to bind events handler. This method sets the event attribute value of the tag to the event handler. This method is not recommended now. HTML and js are coupled, which is not conducive to maintenance.
In js, use the event attribute of the event source (for example, onclick) to bind the event handler function. This method sets the event attribute value of the event source object to the event processing function.
In js, use the addEventListener()
method to bind events and event handling functions (versions before IE9 use the attach Event() method).
1. Use the event attribute binding handler of the HTML tag
It should be noted that using the HTML tag When binding an event handler to an event attribute, the script code in the event attribute cannot contain a function declaration, but can be a function call or a series of script codes separated by semicolons.
[Example 1] Use the event attribute of the HTML tag to bind the event handler.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>使用HTML标签的事件属性绑定事件处理程序</title> </head> <body> <input type="button" onclick="var name='PHP中文网';alert(name);" value="事件绑定测试"/> </body> </html>
The button in the above code is the target object of the click event, which binds two script codes through the event attribute onclick of the label for event processing. After the above code is run in the Chrome browser, when the user clicks the button, a warning dialog box will pop up, and the result is as shown in the figure below.
When the event handler involves more than 2 lines of code, if you still bind the event handler like Example 1, the program will become very readable. Difference. You can do this by defining the event handler as a function and calling the function in the event properties.
[Example 2] The event attribute of the HTML tag is a function call.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>HTML标签的事件属性为函数调用</title> <script> function printName(){ var name = "PHP中文网"; alert(name); } </script> </head> <body> <input type="button" onClick="printName()" value="事件绑定测试"/> </body> </html>
The execution result of the above code is exactly the same as Example 1. As you can see from the above two examples, the tag event attribute mixes JS script code and HTML tags, violating the web standard principle that JS and HTML should be separated. Therefore, it is not good to use the event attributes of HTML tags to bind event handlers, and should be avoided in practical applications.
2. Bind handlers using event attributes of event sources
One of the ways to separate HTML and JS is by using events The event attribute of the source is bound to the event processing function. The binding format is as follows:
obj.on事件名 = 事件处理函数
obj in the format is the event source object. The bound event program is usually the definition statement of an anonymous function, or a function name.
Example of binding handler to event attribute of event source:
oBtn.onclick = function(){//oBtn为事件源对象,它的单击事件绑定了一个匿名函数定义 alert('hi') };
[Example 3] Bind event handler function using event attribute of event source.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>使用事件源的事件属性绑定事件处理函数</title> <script> window.onload = function(){//窗口加载事件绑定了一个匿名函数 //定义一个名为fn的函数 function fn(){ alert('hello'); } //获取事件源对象 var oBtn1 = document.getElementById("btn1"); var oBtn2 = document.getElementById("btn2"); //绑定一个匿名函数 oBtn1.onclick = function(){ alert("hi"); } //绑定一个函数名 oBtn2.onclick = fn; }; </script> </head> <body> <input type="button" id="btn1" value="绑定一个匿名函数"> <input type="button" id="btn2" value="绑定一个函数名"> </body> </html>
The above JS code handles three events: the document window loading event load, and the two button click events click. The processing of these three events is achieved by binding the event processing function using the event attribute of the event source. The load event and the click event of the first button are bound to anonymous functions, while the click event of the second button is bound to an anonymous function. What is determined is a function name.
It is important to note that you cannot add "()" after the function name bound by oBtn2, otherwise the bound function will become a function call, which will automatically occur when the JS engine executes this line of code. The call is executed, but it will not be executed when the event is triggered.
The window loading event function will be processed after all elements of the document are loaded, and the click event will be triggered when each button is clicked. After clicking the first and second buttons, two warning dialog boxes showing "hi" and "hello" will pop up respectively.
##3. Use addEventListener() to bind the handler
Using the event attribute of the event source object to bind event handlers is simple, but it has a shortcoming: an event can only be bound to one handler, and the event handler bound later will overwrite the previously bound event. processing function. In actual applications, an event from an event source may be processed by multiple functions.当一个事件源需要使用多个函数来处理时,可以通过事件源调用 addEventListener()(针对标准浏览器)来绑定事件处理函数以实现此需求。一个事件源通过方法绑定多个事件函数的实现方式是:对事件源对象调用多次 addEventListener(),其中每次的调用只绑定一个事件处理函数。
addEventListener() 是标准事件模型中的一个方法,对所有标准浏览器都有效。使用 addEvent Liste ner() 绑定事件处理程序的格式如下:
事件源.addEventListener(事件名称,事件处理函数名,是否捕获);
参数“事件名称”是一个不带“on”的事件名;参数“是否捕获”是一个布尔值,默认值为 false,取 false 时实现事件冒泡,取 true 时实现事件捕获。
通过多次调用 addEventListener() 可以为一个事件源对象的同一个事件类型绑定多个事件处理函数。当对象发生事件时,所有该事件绑定的事件处理函数就会按照绑定的顺序依次调用执行。另外,需要注意的是,addEventListener() 绑定的事件处理函数中的 this 指向事件源。
addEventListener() 绑定处理程序示例:
document.addEventListener('click',fn1,false);//click事件绑定fn1函数实现事件冒泡 document.addEventListener('click',fn2,true);//click事件绑定fn2函数实现事件捕获
【例 4】使用 addEventListener() 绑定事件函数。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>使用addEventListener()/attachEvent()绑定事件函数</title> <script> function fn1(){ alert("fn1()"); } function fn2(){ alert("fn2()"); } function bindTest(){ document.addEventListener('click',fn1,false);//首先绑定fn1函数 document.addEventListener('click',fn2,false); } bindTest();//调用函数 </script> </head> <body> </body> </html>
上述代码在浏览器中运行后,当单击文档窗口时,会依次弹出显示“fn1()”和“fn2()”的警告对话框。
【推荐学习:javascript高级教程】
The above is the detailed content of How to add events to elements? Three ways to parse JS binding events. For more information, please follow other related articles on the PHP Chinese website!