Assign click handler to newly appended elements
How does one go 开发者_JAVA技巧about adding a click handler in the following example? I need to assign it to the newly appended anchor element.
$.each(regions1, function(key, value) {
var coords = regions1[key].rel.split('-');
$("#map").append("<a href='javascript:void(0)' id='"+ regions1[key].id +"' class='bullet' style='left: "+ addpx(Number(coords[0]) - rempx(settings.bulletWidthOffset)) +"; top: "+ addpx(Number(coords[1]) - rempx(settings.bulletHeightOffset)) +"'> </a> ")
//.click(function(){showPopup(regions1[key].id);})
});
You want to use the .live jQuery keyword.
http://api.jquery.com/live/
$('.bullet').live('click', function() {
// Bound handler called.
});
This sample, btw, needs to sit outside any of your other code and placed within the $(document).ready jQuery method. It will bind a click event to all items that have a class of "bullet".
Try this:
$.each(regions1, function(key, value) {
var coords = regions1[key].rel.split('-');
// first, create the element
var element = $("<a href='javascript:void(0)' id='"+ regions1[key].id +"' class='bullet' style='left: "+ addpx(Number(coords[0]) - rempx(settings.bulletWidthOffset)) +"; top: "+ addpx(Number(coords[1]) - rempx(settings.bulletHeightOffset)) +"'> </a> ");
// then add the listener/handler
element.click(function(){showPopup(regions1[key].id);})
// finally, append the new element to the dom.
$("#map").append( element );
});
精彩评论