The difference between jquery on and bind: 1. The bind method adds an event to each child element, which will affect performance, but the on method will not; 2. When bind dynamically adds elements, the event cannot be dynamically bound. , and the on method can.
The operating environment of this tutorial: Windows 7 system, jquery version 1.10.2. This method is suitable for all brands of computers.
The difference between jquery on and bind:
on() method View the source code and you can find bind()
and delegate()
The bottom layer is implemented using the on() method;
Function signature: bind(type, [data], fn),on(type,[selector],[data],fn).
Give a chestnut:
<html> <head> <meta charset="UTF-8"> <title></title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> </head> <body> <div> <button id="add">添加新的p元素</button> <p>第一个p元素</p> <p>第二个p元素</p> <p>第三个p元素</p> <p>第四个p元素</p> <p>第五个p元素</p> </div> <script> $("#add").click(function(){ $("div").append("<p>这是一个新的p元素</p>"); }); </script>
Usage:
$('div p').bind('click',function(){ alert($(this).text()); }) $("div").on("click","p",function(){ alert($(this).text()); })
Comparison of advantages and disadvantages:
##bind() method:
Disadvantages:1. If there are too many sub-elements, adding an event to each sub-element will affect performance; 2. When adding elements dynamically, Events cannot be dynamically boundAdvantages: It is convenient to write when binding events to a single element. (Ignore)on() method:
1 .Solve the above two shortcomings.2. Use the event delegation mechanism. Instead of directly binding events to the p element, bind events to its parent element (or ancestor element as well). When inside a div When you click on any element, the event will bubble up from the event target layer by layer until it reaches the element for which you have bound the event, and the event will be executed. 3. Problems may also occur when calling. If the event target is very deep in the DOM tree, bubbling up layer by layer to find elements matching the selector will affect performance.Summary:
1. When there are many elements matched by the selector, do not use bind() to iteratively bind 2. When using the id selector, you can use bind()3. Required When binding dynamically added elements, use delegate() or on()4. Use delegate() and on() methods, and the DOM tree should not be too deep5. Try to use on()Related free learning recommendations:javascript (video)
The above is the detailed content of What is the difference between jquery on and bind. For more information, please follow other related articles on the PHP Chinese website!