Event binding in javascript

Source: Internet
Author: User

1. Original syntax <div onclick = "alert ('You clicked me just now); '"> click me </div>, we can't help but write the event binding in html, then we want to separate html and js scripts and write <div id = "test"> click me </div> <script type = "text/javascript"> test. onclick = function () {alert ("you click me just now") ;}; </script> there is no difference in execution between this write method and the previous one, it's just that he looks a little tall. Here, I would like to thank @ con on the eighth floor for reminding me that they are a little different because their execution environments are slightly different and their function scopes contain different objects. For more information, see the message in this article. When we write more complex scripts, we find this "object. the event = event processing function method is not good, because the subsequent events will obviously overwrite the previous event processing function. The result of multiple event binding is usually to execute only the last event processing function, you can refer to the examples in attachEvent and addEventListener. Later, we had to give up this "non-mainstream" approach in actual development. 2. first, attachEvent and addEventListener must be noted that attachEvent is only feasible in Internet Explorer, and addEventListener is feasible in other browsers that follow W3C standards (common browsers can safely use addEventListener ), in IE9 and later versions, you can also use addEventListener. In general, MS had to compromise. It must be noted that the above is an object. event = event processing function. If the attachEvent event binding method is addEventListener without the third parameter, It is a bubble event processing method. As for what is a bubble event and what is a capture event, this involves the DOM Document Object Model and event stream. In short, bubbling means that events are transmitted in the direction from the event target node to the root node of the DOM document structure, capture events are from the root node of the DOM document structure to the event target node. Obj = document. getElementById ("testdiv"); obj. attachEvent ('onclick', function () {alert ('1') ;}); obj. attachEvent ('onclick', function () {alert ('2') ;}); obj. attachEvent ('onclick', function () {alert ('3') ;}); // The execution sequence is alert (3), alert (2 ), alert (1); obj = document. getElementById ("testdiv"); obj. addEventListener ('click', function () {alert ('1') ;}, false); obj. addEventListener ('click', function () {alert ('2') ;}, false); obj. ad DEventListener ('click', function () {alert ('3') ;}, false); // when you click the obj object, the execution sequence is alert ('1 '), alert ('2'), alert ('3'); from this example, we can see that when multiple event processing functions are bound to the same DOM object, attachEvent is first bound and then executed, the addEventListener is first bound and executed. In this case, the events bound to the attachEvent do not conform to the programmer's idea. The event handler function bound to the server must be executed first, it seems that this attachEvent will be eliminated in the near future. AttachEvent must add this "on" to the event bound to the event. If you do not pay attention to it, it is easy to forget to add it. The "on" keyword may be not evolved from the original writing method. After learning the differences between the two functions, we can write some common methods to copy the code function addEvent (elm, evType, fn, useCapture) with IE and other browsers) {if (elm. addEventListener) {elm. addEventListener (evType, fn, useCapture); // W3C standard, based on useCapture to determine whether it is a bubble event or a capture event return true;} else if (elm. attachEvent) {var r = elm. attachEvent ('on' + evType, fn); // IE5 +, only supports bubble event return r;} else {elm ['on' + evType] = fn; // DOM Event} copy the code. Of course, this method also has drawbacks. In IE8 and earlier versions, it is still the first to run the binding after the event and always run it. Bubble events. Alternatively, use the following method: copy the code var addEvent = (function () {if (document. addEventListener) {return function (el, type, fn) {if (el. length) {for (var I = 0; I & el. length; I ++) {addEvent (el [I], type, fn) ;}} else {el. addEventListener (type, fn, false) ;};} else {return function (el, type, fn) {if (el. length) {for (var I = 0; I & el. length; I ++) {addEvent (el [I], type, fn) ;}} else {el. attachEvent ('o N' + type, function () {return fn. call (el, window. event) ;};}}}) (); copy the Code. These are native script event binding methods. Continue copying the Code <div id = "a1" style = "float: left; width: 200px; height: 200px; background-color: red; "> a1 <div id =" a2 "style =" float: left; width: 100px; height: 100px; background-color: blue; "> a2 </div> <script type =" text/script "> a1.addEventListener ('click', function (e) {console. log ('a1') ;}); a2.addEventListener ('click', function (e) {console. log ('a2 '); e. stopPropagation () ;}); </script> E. stopPropagation (). This code can prevent the continuous propagation of events (whether capture or bubble). It should be used frequently in actual development, but IE still does not support it. Event. preventDefault () can block the default action of the Event target, which is not supported by IE. 3. After jQ bind, delegate, on and live have jQ, it is easy to bind all events. The use of bind, delegate, on, and live is not described here. jQ APIs are described in detail. First, bind and bind have solved the problem that the attachEvent of IE is bound first and then executed. See the copy Code <div id = "a1" style = "float: left; width: 200px; height: 200px; background-color: red; "> a1 </div> <script src =" jquery-1.10.2.js "type =" text/javascript "> </script> <script type =" text/javascript ">$ ('# a1 '). bind ('click', function () {console. log ('1 ');}). bind ('click', function () {console. log ('2') ;}); </script> after you copy the code and click a1, the log is first 1 and then 2, consistent with the event binding order. In versions earlier than jQ1.7, the bind method directly attaches the event handler function to the element, and the event handler function is added to the jQuery object of the current element, when many elements are bound to the time processing function, a large amount of storage space is required to store the event processing function. At that time, the recommended method is live, because live adds the event processing function to the document Object, thus saving the space to store the event processing function for each element. However, in Versions later than jQ1.7, With the on method, the live method is canceled, and the on method adds the event handler function to the currently selected jQuery object. In fact, it is equivalent to the delegate method. Copy the <ul id = "ul"> <li> </li> <li> </li> <ul> <script type = 'text/javascript '> $ (' # url '). on ('mouseover', 'lil', function () {alert ('1') ;}); </script> copy the event processing function () in the code above () {alert ('1');} The appended object is ul. Delegate is the event delegate, because it is the delegate, the event is bound to ul, the elements dynamically added to ul can also stimulate the event handler function <script type = 'text/javascript '> $ (' # url') bound to the preceding statement '). delegate ('lil', 'mouseover', function () {alert ('1') ;}); </script> you can see the jQ source code, delegate is equivalent to the on method. Delegate: function (selector, types, data, fn) {return this. on (types, selector, data, fn) ;}, In summary, the recommended event binding methods in jQ are delegate and on, which are equivalent, in Versions later than 1.7, the live method cannot be used, and the bind method can also bind events, but it is best to use bind in a simple element structure. 4. remove <div id = "test"> aaa </div> <script type = "text/javascript"> test. onclick = function () {alert ('1')}; test. onclick = null; </script> This method is actually overwrite. For the attachEvent and addEventListener functions, their relief methods are detachEvent and removeEventListener obj = document. getElementById ("testdiv"); obj. detachEvent ('onclick', function () {alert ('1') ;}); obj. detachEvent ('onclick', function () {alert ('2') ;}); obj. detachEvent ('onclick', function () {alert ('3') ;}); obj = document. getElementById ("testdiv"); obj. removeEventListener ('click', function () {alert ('1') ;}, false); obj. removeEventListe Ner ('click', function () {alert ('2') ;}, false); obj. removeEventListener ('click', function () {alert ('3') ;}, false ); the unbinding of jQ events is bind ----> unbind on ----> off live ----> die delegate ----> undelegate. To prevent the jQ event from being unbound, all methods are removed., you can add a namespace when binding an event to differentiate the copied code $ element. delegate ('. boot ', 'click. dismiss. modal', fn1 ). delegate ('. boot ', 'dblclick. dismis', fn2 ). delegate ('. boot ', 'mouseover', fn3); // do something $ element. undelegate ('. mod Al'); // only unbind fn1 // do something $ element. undelegate ('. dismiss '); // You can unbind both fn1 and fn2, but fn1 has been removed. The effect of this operation is to unbind fn2 // do something $ element. undelegate (); // undo all events. Here, only the fn3 copy code is removed. In addition, if you want to bind the method only once, you can use the one method of jQ, this saves us the trouble of Unbinding events. $ Element. one ('dblclsub', function () {// do something}); // There are many ways to unbind an event, we need to look at the requirements in the Process of timing. The factors to consider are simple, brief, and good performance. At the same time, we need to be compatible with various browsers, so that we can continue to do this.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.