javascript 使用 jquery 将事件附加到未来元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21522499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Attaching event to future elements using jquery
提问by Sumit Shrestha
I am using jquery 1.8 and have to display popup when user clicks some area with class dropdown-toggle. I have attached the events using on while the page loads for the first time.
我正在使用 jquery 1.8 并且必须在用户单击具有类下拉切换的某个区域时显示弹出窗口。我在页面第一次加载时附加了使用 on 的事件。
Here is it
就这个
$('.dropdown-toggle').on("click", function (e) {
console.log("dropdown toggle called");
$(this).next('.dropdown').toggle();
});
$(document).on("click", function (e) {
var target = e.target;
console.log("click toggle called");
if (!$(target).is('.dropdown-toggle') && !$(target).parents().is('.dropdown-toggle')) {
$('.dropdown').hide();
}
});
What i found that second event applies to elements added in future but the first one does not i.e. for a drop down menu added later, only "click toggle called" gets printed in console but for those elements added during start both "click toggle called" and "dropdown toggle called" gets printed.
我发现第二个事件适用于将来添加的元素,但第一个事件不适用于稍后添加的下拉菜单,只有“单击切换调用”会在控制台中打印,但对于在启动期间添加的那些元素,“单击切换调用”和“下拉切换调用”被打印出来。
What is problem here? Does on applies only to document for future element or can it be applied to class or other elements too so that they apply to future elements? If not what is the solution?
这里有什么问题?on 仅适用于未来元素的文档,还是也可以应用于类或其他元素,以便它们适用于未来元素?如果不是,解决方案是什么?
回答by Sergio
You can use delegation with .on(). This way it will listen for a click in document
(it could also be a parent of your element, as long as its present when the event handler is run), when fired look for the element specified as a parameter of the .on().
您可以将委托与.on() 一起使用。这样它就会监听点击document
(它也可以是你元素的父元素,只要它在事件处理程序运行时存在),在触发时查找指定为.on()参数的元素。
Try this:
试试这个:
$(document).on("click", '.dropdown-toggle', function (e) {