的方法可委托的事件,因而不管元素不存在的那一刻,该事件将被创建元素时连接。
在这里,我将模拟的Ajax响应并创建一些元素:
//delegates the "click" event to document and namespace the event with ".nsPopup"
$(document).off(".nsPopup").on("click.nsPopup", ".open-box", function(e) {
e.preventDefault();
var item = $(this).data("item");
//the element with ".open-box" class opens the colorbox
//and display the content of a hidden element
$.colorbox({
html: $(".toShow-" + item).html(), //hidden element
width: 100,
height: 80,
fixed: true,
open: true,
overlayClose: false
});
});
//suppose we generate elements via ajax
function ajaxSuccess (data) {
data = [1,2,3,4,5];
var i = 0, max = data.length;
while(i < max) {
$("<div/>")
.append($("<a href='#' class='open-box'/>").text("link " + data[i]).data("item", i+1))
.append($("<div style='display:none'/>")
.append($("<span/>").addClass("toShow-" + (i+1)).text("Hidden " + data[i])))
.appendTo("body");
i += 1;
}
}
//simulates the success response
ajaxSuccess();
当然,我可以。但我希望每次都避免这种情况。比较类似这样的:'$(document).on('click','a.slideshow',function(){// doStuff});'这将适用于每个新添加的'a.slideshow'。 –