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() {
});
精彩评论