委托事件内的jquery:not()选择器

Som*_*e33 3 jquery

我试图:not()在委托事件中使用选择器,例如

 $('#sidebar-nav').on('click', 'a.documents:not(span)', function(e){

 // code

 });
Run Code Online (Sandbox Code Playgroud)

但它不起作用。那么,如何编写委托单击事件以选择链接而不是其中的<span>元素?必须委派事件,因为所有链接都是动态添加的。

感谢您的任何提示。

Jos*_*ier 5

它没有按预期方式工作,因为选择器a.documents:not(span)将选择具有.documents此类元素的锚元素而不是 span元素(这意味着没有元素将被否定,因为所有锚元素都不是span元素)。

换句话说,:not()伪类不会抑制事件的触发,它只是否定span了被选择元素的锚元素(这意味着它根本没有做任何事情)。

您可以检查是否event.target等于,event.currentTarget以确定是否单击了锚元素(而不是其他后代元素):

$('#sidebar-nav').on('click', 'a.documents', function(event) {
  if (event.target === event.currentTarget) {
    console.log('event.target is the anchor element and not the span.')
  }
});
Run Code Online (Sandbox Code Playgroud)

其中event.currentTarget引用事件侦听器当前附加到的元素(即锚元素);并event.target引用触发click事件的元素。


另外,另一个选择是停止事件在后代span元素上的传播,以防止激发click事件:

$('#sidebar-nav').on('click', 'a.documents', function(event) {
  console.log('Clicked the anchor, not the span.')
});
$('#sidebar-nav').on('click', 'a.documents span', function(event) {
  event.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)

我建议选择第一个选项,因为它绝对更干净。