Javascript jQuery多个选择器,获取哪个选择器触发了事件

Javascript jQuery多个选择器,获取哪个选择器触发了事件,javascript,jquery,Javascript,Jquery,使用多个选择器处理事件时,例如: $('.item a, .another-item a').click(function(e) { }); if($(this).is('.item a')){ //your code here } else if ($(this).is('.another-item a')){ //more here } 是否可以确定哪个父选择器触发了事件?是.item还是另一个item 谢谢大家! 由于选择器几乎可以是任何东西,因此您必须检查具体选项,例如:

使用多个选择器处理事件时,例如:

$('.item a, .another-item a').click(function(e) {

});
if($(this).is('.item a')){
  //your code here
} else if ($(this).is('.another-item a')){
  //more here
}
是否可以确定哪个父选择器触发了事件?是
.item
还是
另一个item


谢谢大家!

由于选择器几乎可以是任何东西,因此您必须检查具体选项,例如:

$('.item a, .another-item a').click(function(e) {

});
if($(this).is('.item a')){
  //your code here
} else if ($(this).is('.another-item a')){
  //more here
}
您可以检查:

var isItem = $( this ).parents( '.item:first' ).length > 0,
    isAnotherItem = $( this ).parents( '.another-item:first' ).length > 0;

您可以使用jQuery
is

if($(this).is('.item a')){
      // code
   }
   else if($(this).is('.another-item a')){//remove 'if ' in case there are only two selector separated by commas.
        //code..

   }
试试这个

$(this).closest('.item').length > 0

如果
.item
,则另一个item
属于两个不同的节点。。然后你可以试试下面的方法

$('.item a, .another-item a').click(function(e) {
    if ($(this).closest('.item').length) {  //if it is '.item'

    } else {

    }
});

是一个标记,而不是
.item
。另一项
选择器是锚定标记,而不是
.item
。另一项
元素如果您根据与元素匹配的选择器更改行为,可能这是您应该分配单独处理程序的指示器。这样就不必在每次事件发生时都测试元素。如果有一些通用代码,请将其放在函数中,并从两个函数中调用它。如果,为什么要调用
?似乎没有必要。@user1689607,以防OP需要添加更多以逗号分隔的选择器。