How to add events to elements? Three ways to parse JS binding events
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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor