JS in the first binding and after binding.

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

This article introduces the front binding and binding in JS, a friend in need for reference

The main meaning is to see I have not used before binding, namely Dom tree of certain elements in has not created, it specifies the type of element birth should have certain events. In the actual development process often involves a front binding and binding. As the name suggests, the front binding — — not yet born binding events, after binding — — born before binding events.

Next, carries on the elaboration through a simple example, for reference, and compares each method:

Page elements:

<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 a tag" id="btnCreate" />

Page JS:

<script src="/js/Scripts/jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
//After binding, i.e. elements cannot be dynamically created with binding events!!!
//1 after the binding
// $("#main > a ").click(function () {
// alert($(this).html());
// });

//2 after the binding
// $("#main > a").bind("click", function () {
// alert($(this).text());
// });

//3 after the 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 binding, dynamically created elements also have the click event
// $("#main").delegate("a", "click", function () {
// alert($(this).text());
// });

//5 binding, live event source is the source of the documentdelegate is specific to the binding element, so the efficiency of delegate is higher than live.
$("#main a").live("click", function () {
alert($(this).text());
});
}); //Source: www.jbxue.com
</script>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Alex at November 13, 2013 - 1:31 PM