我有一个人搜索脚本,它会在你键入时显示建议。结果的结构大致如下:
<div id="peopleResults">
<div class="resultHolder">
<div data-userid="ABC123" class="person">
<div class="name">Last, First</div>
<div class="title">Job Title</div>
<a class="email" href="mailto:person@company.com">person@company.com</a><span class="phone">12345</span>
</div>
<!-- more people... -->
</div>
</div>由于人员列表会随着您的输入而改变,到目前为止,我一直使用JQuery的live()函数自动将单击事件绑定到所有.person元素。这种做法已被弃用,而且是糟糕的做法,因此我正在尝试更新代码。
我发现我可以使用如下内容:
$('#peopleResults').on('click', '.person', function(){
// handle the click
})但是我想了解更多关于如何在vanilla javascript中处理这个问题。我认为,当使用单击事件单击项目的子项时,该事件会在元素中“冒泡”起来,当它命中.person元素时,我可以捕捉到它。请原谅我草率的代码,但类似于:
document.getElementById('peopleResults').addEventListener('click', function(e){
if(e.target.classList.contains('person')) {
// handle click
}
});我以前也做过类似的事情,但通常是使用链接。(在这种情况下,.person不能是链接,因为它包含电子邮件链接。)
所以在这种情况下,它不起作用。如果我在.person中单击.name,则目标是.name。
这似乎是一些基本的东西,只是没有在我的大脑中点击。在JavaScript中处理这个问题的典型方法是什么?
发布于 2014-12-03 23:45:04
您可以将所需目标的所有子目标的pointer-events设置为none:
.person > * {
pointer-events: none;
}这样,event.target将是一个.person元素,而不是它的子元素之一。
document.getElementById('peopleResults').addEventListener('click', function(e){
if(e.target.classList.contains('person')) {
alert('Person clicked');
}
});.person > * {
pointer-events: none;
}<div id="peopleResults">
<div class="resultHolder">
<div data-userid="ABC123" class="person">
<div class="name">Last, First</div>
<div class="title">Job Title</div>
<a class="email" href="mailto:person@company.com">person@company.com</a><span class="phone">12345</span>
</div>
<!-- more people... -->
</div>
</div>
请注意,这种方法将破坏.person中的交互式元素(如链接)的功能。
发布于 2014-12-04 00:11:43
在使用jQuery事件时,会为您提供两个您应该熟悉的属性:
targetcurrentTarget当使用事件委托(即捕捉父元素上的事件)时,target将是最初触发事件的元素,而currentTarget将是捕捉事件的元素。
考虑下面的代码示例:
$('#peopleResults').on('click', '.person', function(e) {
if ($(e.currentTarget).hasClass('person')) console.log('yay!');
});附注:当不使用事件委托时,两个属性应该指向相同的元素。
有关currentTarget的更多信息。
https://stackoverflow.com/questions/27275279
复制相似问题