The difference between jQuery: $ (). click () and $ (document ). on ('click', 'element to be selected ', function () {}), jquery. click
The emergence of jQuery greatly simplifies dom operations. However, if you do not carefully read the api and perform operations, you do not know the biggest advantages and usage methods. Take $ (). click () and $ (document ). for on ('click', 'element to be selected ', function () {}), they are all click event operations, but they are also different.
1. $ (selector). click (fn)
The callback function fn is triggered when the selected selector is clicked. Only for the selector that already exists with the page.
<body> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <script src="jquery.min.js"></script> <script> $(function(){ $('ul>li').click(function(){ console.log($(this).html()); }); $('ul').append('<li>5</li><li>6</li>'); }) </script></body>
The result is as follows:You cannot trigger a click event for the 5 and 6 dynamically created later..
2. $ (document). on ('click', 'element to be select', function (){})
The on method contains many events, such as click and double-click events. Like $ (). click (), the biggest difference is that a callback function can be triggered if the dynamically created element is within the selected range of the selector.
<body> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <script src="jquery.min.js"></script> <script> $(function(){ $('body').on('click','ul>li',function(){ console.log($(this).html()); }); $('ul').append('<li>5</li><li>6</li>'); }) </script></body>
The result is as follows:The dynamically added element can also be clicked to trigger the function..
Add the following knowledge points for $ (). on:
1. Starting from jQuery 1.7, on()
Functions provide all the functions required to bind the event handler. They are used to replace the previous bind (), delegate (), live () and other event functions.
$ (). Bind () is directly bound to an element. It is the same as click, blur, and mouseon.
$ (). Live () is bound to an element by means of bubbling. More suitable for the list type, bind to the document DOM node.
$ (). Delegate () is a more precise event proxy in a small scope.
$ (). On () combines the advantages of these three methods to discard the disadvantages.
2. This function can bind multiple event handlers to the same element and event type. When an event is triggered, jQuery executes the Bound event processing function in sequence according to the binding sequence.
3. methods to prevent event bubbles and event delegation:
A: return false.
In event processing, you can block default events and bubble events.
B: event. preventDefault ()
In event processing, you can prevent default events but allow the occurrence of bubble events.
C: event. stopPropagation ()..
In event processing, you can prevent bubbling but allow the occurrence of default events.