The methods of event processing in JavaScript are: 1. Add an event in the event attribute of the tag, the syntax is "
"; 2. Use the event source The event attribute is bound to the event processing function, the syntax is "event source object.on event name = event processing function".
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.
Javascript event processing method
Method 1. Add an event in the event attribute of the tag
Use the event attribute of the HTML tag to bind the handler. It should be noted that when using the event attribute of an HTML tag to bind an event handler, 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:
<!doctype html> <html> <head> <meta charset="utf-8"> <script> function printName(){ var name = "张三"; alert(name); } </script> </head> <body> <input type="button" onClick="printName()" value="事件绑定测试"/> </body> </html>
Method 2. Use the event attribute of the event source to bind the handler
One way to separate HTML and JS is to bind event processing functions by using the event attribute of the event source. 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 a handler to the event attribute of the event source:
oBtn.onclick = function(){//oBtn为事件源对象,它的单击事件绑定了一个匿名函数定义 alert('hi') };
Example: Binding an event handler function using the event attribute of the event source.
<!doctype html> <html> <head> <meta charset="utf-8"> <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>
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of What are the methods of event handling in javascript. For more information, please follow other related articles on the PHP Chinese website!