开发者

jQuery click not working on appended dom

I appended some div like this :

var to = "Some 开发者_Python百科content"
$("#key").append("<div class=\"cont\">"+to+"  <span ded="+ lastid +" class=\"\contspan\">X</span></div>  ");

Then i tried to bind a click on event on the div with class cont by doing this :

$('.cont').delegate('div', 'click', function() {
    $("#logger").html("click")
});

But this doesnt works ? Where have i been going wrong ?

EDIT: I tried to place a bacground color to the class cont And the color is there to show that class id added fine


You aren't using delegate quite right, try this:

$('#key').delegate('div.cont', 'click', function() {
    //var text1 = $(this).attr("ded");
    $("#logger").html("click")
});

You call the delegate method on the element that isn't going to change ('#key') and then pass it the selector for the dynamic element ('div.cont') as the first parameter.


You have no <div> in your .cont there

http://sandbox.phpcode.eu/g/1cbbd.php

<div id="key"> 

</div> 
<div id="logger"> 
</div> 
<script> 
var to = "Some content"; 
var lastid = "test"; 
$("#key").append("<div class='cont'>"+to+"<span ded='"+ lastid +"' class='contspan'>X</span></div> "); 
$('.cont').delegate('span', 'click', function() { 
    //var text1 = $(this).attr("ded"); 
    $("#logger").html("click") 
}); 
</script> 


Try using .live() function instead of delegate.

$('.cont').live('click', function() {
    // var text1 = $(this).attr("ded");
    $("#logger").html("click");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜