jQuery当前目标在多个选择中

时间:2011-02-17 14:52:26

标签: javascript jquery target

如何检索我的哪一个选择是我的“当前”目标? 我希望在这个函数中有不同的变量。

$('#header a, #nav a').click(function (event) {

// if is $('#header a')  do this
// if is $('#nav a')  do that   

});

2 个答案:

答案 0 :(得分:4)

this会引用实际的DOM元素,因此您可以检查tagNameclassName,或查找$(this).parents('#header')

$('#header a, #nav a').click(function (event) {
  var $this = $(this);

  if ($this.parents("#header").length > 0) {
    display("I'm inside #header");
  }
  else if ($this.parents("#nav").length > 0) {
    display("I'm inside #nav");
  }
  else {
    // Obviously this won't happen.
    // None of us has *ever* changed a selector and forgotten to update the code! ;-)
    display("I'm confused!");
  }

  return false;

});

Live example


偏离主题:我同意Felix和melaos的说法,如果你真的在做不同的事情,那么重构成单独的处理程序(也许是调用常用函数)可能是更好的方法。

答案 1 :(得分:1)

this 引用选择器的匹配集合中的当前元素。 但是,如果需要以不同方式处理每个元素,为什么要将元素的click事件绑定为一个组(即使用单个选择器)。

为了更好地管理代码,我将使用两个绑定调用,如:

$("#header a").click(function (event) {
 //Do what you need to do for #header a
}); 

$("#nav a").click(function (event) {
 //Do what you need to do for #nav a
});