I have simple html markup:
<div id="cont">Some text here
<div class="wrap" style="border: 1px solid black;display: inline;"> block element here
</div> and another text</div>
And jQuery code:
$(function(){
$(".wrap").click(function(){
$("#cont").html($("#cont").html().replace(/text/g, "letter"));
alert("Click!");
});
$开发者_开发知识库("#d1").click(function(){
alert("#d1 clicked!");
});
});
I expect that click event will be fire any time you clicked by the #d1
div, but when we clicked by .wrap it neve fire again. I understand why it has such behavior, but how to solve it?
#d1
after $("#cont").html($("#cont").html().replace(/text/g, "letter"))
because I don't now at execution time if event was set.
You can try example on JSBin
Thanks for replies, live() is a very useful function.
DEMO: http://jsbin.com/aqono4/4/edit
If you are unsure of the state of your elements you can always use live
to bind your events:
$(function(){
$(".wrap").live('click', function(){
$("#cont").html($("#cont").html().replace(/text/g, "letter"));
alert("Click!");
});
$("#d1").live('click', function(){
alert("#d1 clicked!");
});
});
Events bound with the live method, will still apply to instances found after the code is initially called.
DEMO: http://jsbin.com/aqono4/4/edit
You should bind using the live()
method.
$(function(){
$(".wrap").live("click", function() {
// ....
As GvS said, bind the event. When you dont need it, you can unbind.
精彩评论