我有两个这样的功能:
function fn1() {
$(".element").append("<div class='trigger'></div>");
}
function fn2() {
$(".element").append("<div class='trigger'></div>");
}
和一位听众:
$(".trigger").click(function() {
// do some magic with $(this) element
});
问题是如果click事件侦听器位于fn1和fn2之外,则它不会看到动态创建的元素(触发器)何时被单击。
如何让事件监听器全局监听?
答案 0 :(得分:9)
<强> jsFiddle Demo
强>
使用 on
.trigger
的所有当前和未来实例
$("body").on("click",".trigger",function() {
// do some magic with $(this) element
});
修改的
<强> jsFiddle Demo
强>
Re:你能否建议如何使用on语句创建悬停监听器?
哈佛确实是一个极端的案例。使用流畅的方法,您可以使用$().hover(function(){},function(){})
。但是,使用on
不是这种情况。为了使用它,您实际上必须使用两个单独的委托 mouseenter
和 mouseleave
$("body").on("mouseenter",".trigger",function() {
// do some magic with $(this) element
});
$("body").on("mouseleave",".trigger",function() {
// do some magic with $(this) element
});
答案 1 :(得分:0)
试试这个:
$("body").on("click", ".trigger", function() {
// do some magic with $(this) element
});