<div id="divTestArea1">
<a href="javascript:void(0);" onclick="AddBox();">Add box</a>
<div class="test">This is a box</div>
</div>
<script type="text/javascript">
$(function()
{
$(".test").bind("mouseover", function()
{
$(this).css("background-color", "blue");
}).bind("mouseout", function()
{
$(this).css("background-color", "white");
});
});
function AddBox()
{
var div = $("<div></div>").addClass("test").text("Another box");
$("#divTestArea1").append(div);
}
</script>
Okay, this example might seem a bit complicated, but actually it's not. Let me walk you through it. We have a link, which will call the AddBox() JavaScript method, and then we have a div with the class "test". The AddBox() method will simply add another div to the page, with the same class, so that when you click the link, you get yet another box on the page. In the ready event, we select all elements with the "test" class and then we bind a handler to two of the events: The mouseover and the mouseout event, where we change the color of the element invoking the event. Try the example in your browser. The first div will have the mouseover effect, but if you click the link to add more boxes, they won't have the same effect. The reason is pretty obvious: We attached the events before these new boxes were created.
Now try the following example instead. I have only changed two words in it: The two calls to bind() has been replaced with calls to live():
<div id="divTestArea2">
<a href="javascript:void(0);" onclick="AddBox();">Add box</a>
<div class="test">This is a box</div>
</div>
<script type="text/javascript">
$(function()
{
$(".test").live("mouseover", function()
{
$(this).css("background-color", "blue");
}).live("mouseout", function()
{
$(this).css("background-color", "white");
});
});
function AddBox()
{
var div = $("<div></div>").addClass("test").text("Another box");
$("#divTestArea2").append(div);
}
</script>
Now if you run this example, you will see that even though you add new elements after the page has loaded, jQuery will automatically attach the event handlers to them for you. The live() method works just like bind() in all the other aspects, so check the previous chapters for more information on it. The same goes for the die() method, which works just like the unbind() method, but should be used for cases where the live() method has been used.
No comments:
Post a Comment