This article details the pre-binding and post-binding in JS, the need for friends can refer to
The main meaning is to see if I have used the pre-binding, that is, some elements in the DOM tree have not yet been created, specify the elements of that type should have some events born. Pre-binding and post binding are often involved in the actual development process. As the name suggests, pre-binding--not yet born--binds certain events, then binds--some events that are bound after birth.
Below, through a simple example to illustrate, for everyone to refer to, and compare the various methods:
Page elements:
Copy Code code as follows:
<div id= "main" >
<a href= "#" >aaaaaaaaaaaaaaaaaaaaaa</a><br/>
<a href= "#" >bbbbbbbbbbbbbbbbbbbb</a><br/>
<a href= "#" >ccccccccccccccccccccccccc</a><br/>
<a href= "#" >dddddddddddddddddddd</a><br/>
<a href= "#" >eeeeeeeeeeeeeeeeeeeeee</a><br/>
<a href= "#" >fffffffffffffffffffffffffffffffff</a><br/>
<a href= "#" >gggggggggggggggggggg</a><br/>
<a href= "#" >hhhhhhhhhhhhhhhhhhhh</a>
</div>
<input type= "button" value= "Create a Label" id= "Btncreate"/>
JS in the page:
Copy Code code as follows:
<script src= "201102/scripts/jquery-1.5.js" type= "Text/javascript" ></script>
<script type= "Text/javascript" >
$ (function () {
//After binding, that is, dynamically created elements cannot have bound events!!!
//1.
after binding
//$ ("#main > A"). Click (function () {
//Alert ($ (this). html ());
// });
2. Post Binding
$ ("#main > A"). Bind ("click", Function () {
Alert ($ (this). text ());
// });
3. After binding,
$ ("#main > A"). Bind ({
Click:function () {Alert ($ (this). text ());
Mouseover:function () {$ (this). CSS ("Background-color", "Red")},
Mouseout:function () {$ (this). CSS ("Background-color", "White")}
// });
$ ("#btnCreate"). Bind ({
Click:function () {$ ("<br/><a href= ' > I am a dynamically created </a>"). Appendto ("#main");
});
4. Pre-binding, dynamically created elements also have clicked events
$ ("#main"). Delegate ("A", "click", Function () {
Alert ($ (this). text ());
// });
5. Pre-binding, live event source is the source of documentdelegate is the specific elements to be bound, so delegate efficiency than live much higher
$ ("#main a"). Live ("Click", Function () {
Alert ($ (this). text ());
});
});
</script>