多个选择器:识别触发器? [英] Multiple selectors: identify the triggering one?

查看:90
本文介绍了多个选择器:识别触发器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here's a very small issue that I was unable to figure out. I'm sure someone can answer in no time:

有多个选择器,如

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

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

, how can I figure out which selector was actually clicked? I need to use it like $(clicked_element)....

谢谢。

推荐答案

使用$(this)将获得被点击的元素..并使用是()可以帮助您确定点击的内容。

Using $(this) will get you the element that was clicked.. and using is() can help you determine what was clicked.

$('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);
   }
});






已编辑:

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

As I wrote up this answer it seems there is a better approach. Patrick DW's comment intrigued me and I wanted to know more. His clarification is here jQuery - Issues with combining selectors in a single event handler

这会更好方法

$("a.button").click(function (e) { ... });
$("span.xyz").click(function (e) { ... });
$("a.another").click(function (e) { ... });

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

As I understand it if your goal was to place common functionality in one spot then this is how it should be handled

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) { ... });

这篇关于多个选择器:识别触发器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆