使用jquery将事件附加到未来的元素 [英] Attaching event to future elements using jquery
问题描述
这是它
$('。dropdown-toggle' ).on(click,function(e){
console.log(dropdown toggle called);
$(this).next('。dropdown')。 b $ b});
$(document).on(click,function(e){
var target = e.target;
console.log(click toggle called);
如果(!$(target).is('。dropdown-toggle')&!$(target).parents()。is('。dropdown-toggle')){
$(' drop();
}
});
我发现第二个事件适用于将来添加的元素,但第一个不适用于稍后添加下拉菜单,只有点击切换被调用才能打印在控制台中,但是在启动过程中添加的元素将打印click toggle和dropdown toggle called。
这里有什么问题?是否仅适用于未来要素的文件,还是适用于课堂或其他元素,以便适用于未来的元素?如果不是解决方案?
您可以使用代理与 .on() 。这样,它会收听文档
中的点击(它也可以是元素的父级,只要它在当前事件处理程序运行时),被触发时对于指定为 .on()的参数的元素。
尝试这样:
$ b $ ($)$($)$($)$($)pre>
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.
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?
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().
Try this:
$(document).on("click", '.dropdown-toggle', function (e) {
这篇关于使用jquery将事件附加到未来的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!