多个选择器:识别触发器?

bob*_*oap 4 javascript jquery jquery-selectors

这是一个我无法弄清楚的非常小的问题.我相信有人可以立即回答:

有多个选择器喜欢

$('a.button, span.xyz, a.another').click(function(e) {
   var clicked_element = ???;
});
Run Code Online (Sandbox Code Playgroud)

,我该如何确定实际点击了哪个选择器?我需要像使用它一样$(clicked_element)....

谢谢.

Joh*_*ock 6

使用$(this)将获得单击的元素..并且使用is()可以帮助您确定单击的内容.

$('a.button, span.xyz, a.another').click(function(e) {
   if ($(this).is("a.button")) {
     alert("a.button was clicked");
   } else if ($(this).is("span.xyz")) {
     alert("span.xyz was clicked");
   } else if($(this).is("a.another")) {
     alert("a.another was clicked);
   }
});
Run Code Online (Sandbox Code Playgroud)

编辑:

当我写下这个答案时,似乎有一个更好的方法.Patrick DW的评论引起了我的兴趣,我想知道更多.他的澄清是jQuery - 在单个事件处理程序中组合选择器的问题

这将是一种更好的方法

$("a.button").click(function (e) { ... });
$("span.xyz").click(function (e) { ... });
$("a.another").click(function (e) { ... });
Run Code Online (Sandbox Code Playgroud)

据我了解,如果您的目标是将常用功能放在一个位置,那么这就应该如何处理

function commonFunctionality(elementSelector) {
   // common code for all elements here or at the end

   switch (elementSelector) {
     case "a.button":
       //do stuff for a.button only;
       break;
     case "span.xyz":
       //do stuff for span.xyz only;
       break;
     case "a.another":
       //do stuff for a.another only;
       break;
   }

   // common code for all elements
}


$("a.button").click(function (e) { ... });
$("span.xyz").click(function (e) { ... });
$("a.another").click(function (e) { ... });
Run Code Online (Sandbox Code Playgroud)