【发布时间】:2017-12-03 12:49:03
【问题描述】:
http://jsbin.com/xaguxuhiwu/1/edit?html,js,console,output
<div id="container">
<button id="foo">Foo button</button>
<button id="bar">Bar button</button>
</div>
$('#container').on('click', function(e) {
var targetId = e.target.getAttribute('id');
// Manually do event delegation
if (targetId === 'foo') {
var currentId = e.currentTarget.getAttribute('id');
console.log('without delegation, currentTarget is: ' + currentId);
}
});
$('#container').on('click', '#foo', function(e) {
var currentId = e.currentTarget.getAttribute('id');
console.log('with delegation, currentTarget is: ' + currentId);
});
基本上,我对事件的 e.currentTarget 的理解是它反映了事件冒泡到的点。由于我在 #container 元素上有一个事件侦听器,因此我希望 currentTarget 在这两种情况下都是 container。
这对于标准的on 处理程序是正确的,如第一个示例所示。但是,当使用事件委托(第二次点击时的 #foo 参数)时,currentTarget 会变为内部按钮。
为什么e.currentTarget 在两种情况下会发生变化?
具体来说,在后一种情况下,这是否意味着 jQuery 没有将事件监听器放在父 (#container) 元素上?
【问题讨论】:
-
在第二个函数中,你是在告诉 jquery“当我点击一个 id="foo" 的元素时触发事件,该元素嵌套在 id="container" 元素的某处。另外,由于您正在预加载 html 元素,而不是在 DOM 加载后插入,因此从技术上讲,您不需要
.on,并且在第二个函数中,您可以访问元素#foo而无需首先引用元素#container. -
另外,您可以使用
this,而不是使用e.currentTarget。使用 vanilla JS,您可以在 jQuery 中将e.currentTarget.getAttribute('id')更改为this.id和$(this).attr('id')。 -
@AaronEveleth:这不是我对 jQuery 中的
.on的理解。.on()应该为前面选择器中的任何元素添加一个侦听器。当您添加第二个参数(也就是使用事件委托)时,我的理解是 jQuery 不会调用回调函数,除非event.target匹配选择器。 -
关于
this,我的问题是关于currentTarget。该属性在 DOM 中具有特定的语义。要么 jQuery 出于某种未知原因修改了 currentTarget,要么事件处理程序的实际绑定方式与预期不同。 -
标签: javascript jquery dom