我有一些代码,我循环遍历页面上的所有选择框并绑定(bind) .hover
事件让他们在 mouse on/off
上做一些调整宽度.
这发生在页面准备好并且工作正常。
我遇到的问题是,在初始循环之后通过 Ajax 或 DOM 添加的任何选择框都不会绑定(bind)事件。
我已经找到了这个插件( jQuery Live Query Plugin ),但在我使用插件向我的页面添加另一个 5k 之前,我想看看是否有人知道如何做到这一点,无论是直接使用 jQuery 还是通过其他选项。
最佳答案
从 jQuery 1.7 开始,您应该使用 jQuery.fn.on
填充选择器参数:
$(staticAncestors).on(eventName, dynamicChild, function() {});
说明:
这称为事件委托(delegate),其工作原理如下。该事件附加到应处理的元素的静态父级 (staticAncestors
)。每次在此元素或后代元素之一上触发事件时,都会触发此 jQuery 处理程序。然后,处理程序检查触发事件的元素是否与您的选择器 (dynamicChild
) 匹配。当存在匹配时,就会执行您的自定义处理程序函数。
在此之前,推荐的方法是使用 live()
:
$(selector).live( eventName, function(){} );
但是,live()
在 1.7 中已被弃用,取而代之的是 on()
,并在 1.9 中完全删除。 live()
签名:
$(selector).live( eventName, function(){} );
...可以替换为以下on()
签名:
$(document).on( eventName, selector, function(){} );
<小时/>
例如,如果您的页面动态创建具有类名 dosomething
的元素,您可以将该事件绑定(bind)到已经存在的父级(这是该事件的核心)这里的问题是,你需要一些存在的东西来绑定(bind),而不是绑定(bind)到动态内容),这可以是(也是最简单的选项)是document
。但请记住document
may not be the most efficient option .
$(document).on('mouseover mouseout', '.dosomething', function(){
// what you want to happen when mouseover and mouseout
// occurs on elements that match '.dosomething'
});
事件绑定(bind)时存在的任何父级都可以。例如
$('.buttons').on('click', 'button', function(){
// do something here
});
适用于
<div class="buttons">
<!-- <button>s that are generated dynamically and added here -->
</div>
关于javascript - 动态创建的元素上的事件绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39276709/