开发者

Why isn't my bound event being applied to newly created elements?

开发者 https://www.devze.com 2023-04-03 11:57 出处:网络
I\'m have a click function which adds an image 开发者_运维问答to a div with a class of \"selectedimage\". I\'m trying to create another click function which references \"selectedimage\", however, it w

I'm have a click function which adds an image 开发者_运维问答to a div with a class of "selectedimage". I'm trying to create another click function which references "selectedimage", however, it will not initiate. Is this because it didn't exist when the DOM was first loaded? Thanks.

$(".articlethumb").bind('click', function() {
var currentid = $(this).attr("id");
var medium = $(this).find(".thumb-medium").text();
var mediumimage = "<img id='" + currentid + "' class='selectedimage' src='" + medium + "' />";
$("#mainimage").html(mediumimage);
});

$(".selectedimage").bind('click', function() {
alert("test");
});


Use .live.

$('.articlethumb').live('click',function(){
    your code here
})

As you suspected it has to do with the element not being in the dom when the event is bound, and live fixes this.


Instead of using "bind", use "live". Same syntax, except live will apply the event handlers to any existing matching elements, and any future (as-yet non-existant) matching elements.


.bind only affects elements already in the DOM.

To "bind" an event to all existing and future elements, use .live:

$('selector').live(click, function() {

});
0

精彩评论

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

关注公众号