Jquery learning-Event Response (bind, live, delegate) to dynamically created elements)
Event Response
In fact, we usually respond to elements on the web page, such as onclick and onchange events, which are relatively simple. Because jquery is encapsulated$('elementID').click()
You can.
Dynamically add elements
Using js to control the addition and deletion of page elements is a very frequent operation, and it is easy to find that our page code is as follows:
<Script src = "http://www.w3school.com.cn/jquery/jquery.js"> </script> <script> $ (document ). ready (function () {$ ('# btnone '). click (function () {$ ('. row '). append (' Button 2') ;}); $ (' # Btntwo'). click (function () {alert ("click me! ") ;}); </Script>
Button 1
It is easy to see that there is only oneButton 1
When we click,Button 2
In fact, we have already writtenButton 2
But no matter how we click, we find that there will be no changes at all.
This is because the elements that do not exist on the page at the beginning, jquery'sclick
Is not bound to the element.
Cause:
Because the click or change methods are implemented using bind.
Bind dynamic elements
Since bind cannot be implemented, what can be implemented?
Live () delegate ()
Both can be implemented. Both methods can respond to events that do not exist in the DOM. So the above Code:
$('#btntwo').click(function() { alert("click me!"); });
Use the following code:
$('#btntwo').live('click', function() { alert("click me!"); });
Or use the following code:
$(document).delegate('#btntwo', 'click', function() { alert("click me!"); });
It will take effect.
Different live and delegate
I checked the W3c live page and W3c delegate page and found that.
It seems that the only difference is:
Live
The live () method attaches one or more event handlers to the selected elements and specifies the functions that run when these events occur.
Delegate
The delegate () method adds one or more event handlers to the specified element (a child element of the selected element) and specifies the function to run when these events occur.
That is, delegate is the child element of the specified element to be processed.
To learn more about the usage of the two functions, click the two hyperlinks above to view details.