Method: 1. Use the event attribute onclick of the HTML tag to bind the handler, with the syntax "onclick="event handler""; 2. Use the event attribute of the event source to bind the handler, with the syntax "obj. on event name = handler function"; 3. Use addEventListener() to bind the handler.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
In order for the browser to automatically call the corresponding event handler to handle the event when the event occurs, it is necessary to bind the event handler to the event source (the bound event handler is also called a registered event handler).
There are 3 ways to bind event handlers:
- ##Use the event attribute onclick of the HTML tag to bind the event handler. This method sets the event attribute value of the tag to the event handler. This method is not recommended now.
- Use the event attribute of the event source to bind the event handler function. This method sets the event attribute value of the event source object to the event processing function.
- Use the addEventListener() method to bind events and event handling functions (versions before IE9 use the attach Event() method.
1. Use the event attribute of the HTML tag to bind the handler.
It should be noted that when using the event attribute of the HTML tag to bind the event handler, the event The script code in the attribute cannot contain a function declaration, but can be a function call or a series of script codes separated by semicolons.[Example 1] Bind an event handler using the event attribute of the HTML tag .
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>使用HTML標(biāo)簽的事件屬性綁定事件處理程序</title> </head> <body> <input type="button" onclick="var name='PHP中文網(wǎng)';alert(name);" value="事件綁定測(cè)試"/> </body> </html>The button of 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. The above code is run after 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.
[Example 2] The event attribute of the HTML tag is a function call.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>HTML標(biāo)簽的事件屬性為函數(shù)調(diào)用</title> <script> function printName(){ var name = "PHP中文網(wǎng)"; alert(name); } </script> </head> <body> <input type="button" onClick="printName()" value="事件綁定測(cè)試"/> </body> </html>The execution result of the above code is exactly the same as Example 1. As can be seen from the above two examples, the tag event attribute will JS script code and HTML tags are mixed together, which violates the Web standard principle that JS and HTML should be separated. Therefore, it is not good to use the event attribute of HTML tags to bind event handlers, and should be avoided in actual applications.
2. Bind handlers using event attributes of event sources
One of the ways to separate HTML and JS is by using event sources. The event attribute binds the event processing function. The binding format is as follows:obj.on事件名 = 事件處理函數(shù)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 event attribute binding handler of event source:
oBtn.onclick = function(){//oBtn為事件源對(duì)象,它的單擊事件綁定了一個(gè)匿名函數(shù)定義 alert('hi') };
[Example 3]Use the event attribute of event source to bind event handler function.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>使用事件源的事件屬性綁定事件處理函數(shù)</title> <script> window.onload = function(){//窗口加載事件綁定了一個(gè)匿名函數(shù) //定義一個(gè)名為fn的函數(shù) function fn(){ alert('hello'); } //獲取事件源對(duì)象 var oBtn1 = document.getElementById("btn1"); var oBtn2 = document.getElementById("btn2"); //綁定一個(gè)匿名函數(shù) oBtn1.onclick = function(){ alert("hi"); } //綁定一個(gè)函數(shù)名 oBtn2.onclick = fn; }; </script> </head> <body> <input type="button" id="btn1" value="綁定一個(gè)匿名函數(shù)"> <input type="button" id="btn2" value="綁定一個(gè)函數(shù)名"> </body> </html>Three events are processed in the above JS code: the document window loading event load and the click event of the two buttons. 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 an anonymous function, while the click event of the second button is bound to 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 handlerUsing 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.
當(dāng)一個(gè)事件源需要使用多個(gè)函數(shù)來(lái)處理時(shí),可以通過事件源調(diào)用 addEventListener()(針對(duì)標(biāo)準(zhǔn)瀏覽器)來(lái)綁定事件處理函數(shù)以實(shí)現(xiàn)此需求。一個(gè)事件源通過方法綁定多個(gè)事件函數(shù)的實(shí)現(xiàn)方式是:對(duì)事件源對(duì)象調(diào)用多次 addEventListener(),其中每次的調(diào)用只綁定一個(gè)事件處理函數(shù)。
addEventListener() 是標(biāo)準(zhǔn)事件模型中的一個(gè)方法,對(duì)所有標(biāo)準(zhǔn)瀏覽器都有效。使用 addEvent Liste ner() 綁定事件處理程序的格式如下:
事件源.addEventListener(事件名稱,事件處理函數(shù)名,是否捕獲);
參數(shù)“事件名稱”是一個(gè)不帶“on”的事件名;參數(shù)“是否捕獲”是一個(gè)布爾值,默認(rèn)值為 false,取 false 時(shí)實(shí)現(xiàn)事件冒泡,取 true 時(shí)實(shí)現(xiàn)事件捕獲。
通過多次調(diào)用 addEventListener() 可以為一個(gè)事件源對(duì)象的同一個(gè)事件類型綁定多個(gè)事件處理函數(shù)。當(dāng)對(duì)象發(fā)生事件時(shí),所有該事件綁定的事件處理函數(shù)就會(huì)按照綁定的順序依次調(diào)用執(zhí)行。另外,需要注意的是,addEventListener() 綁定的事件處理函數(shù)中的 this 指向事件源。
addEventListener() 綁定處理程序示例:
document.addEventListener('click',fn1,false);//click事件綁定fn1函數(shù)實(shí)現(xiàn)事件冒泡 document.addEventListener('click',fn2,true);//click事件綁定fn2函數(shù)實(shí)現(xiàn)事件捕獲
【例 4】使用 addEventListener() 綁定事件函數(shù)。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>使用addEventListener()/attachEvent()綁定事件函數(shù)</title> <script> function fn1(){ alert("fn1()"); } function fn2(){ alert("fn2()"); } function bindTest(){ document.addEventListener('click',fn1,false);//首先綁定fn1函數(shù) document.addEventListener('click',fn2,false); } bindTest();//調(diào)用函數(shù) </script> </head> <body> </body> </html>
上述代碼在瀏覽器中運(yùn)行后,當(dāng)單擊文檔窗口時(shí),會(huì)依次彈出顯示“fn1()”和“fn2()”的警告對(duì)話框。
【推薦學(xué)習(xí):javascript高級(jí)教程】
The above is the detailed content of How to bind events in javascript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
