在 jQuery 中,我的事件处理程序的工作方式有所不同,具体取决于我是否拆分选择器。
选择器未拆分(#myId .someClass):
$('#myId .someClass').on('click', function (e) {
alert('x');
});
选择器“split”(#myId ........ .someClass):
$('#myId').on('click', '.someClass', function (e) {
alert('x');
});
当我使用后者时,我会通过同一次点击多次获得相同的事件,而第一个只会给我一次点击事件(但是我有时会遇到第一个甚至不起作用)。
谁能解释一下为什么会出现这种差异?
最佳答案
差异在于例如第一个版本
$('#myId .someClass').on('click', function (e) { ...
将点击事件绑定(bind)到所有 .someClass
元素,这些元素是 id 为 #myId
的元素的后代,并且在页面加载时已经在 DOM 中,而第二个版本
$('#myId').on('click', '.someClass', function (e) { ..
会将 #myId
元素中的点击事件委托(delegate)给具有 .someClass
类的所有后代元素,即使它们是稍后动态添加的。
作为其中的一个重要引用,“直接和委托(delegate)事件”部分:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().
关于javascript - jQuery 和事件处理程序,为什么我拆分选择器很重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27681936/