开发者

jQuery current target in multiple selection

开发者 https://www.devze.com 2023-02-11 11:14 出处:网络
how can i retrieve which one of my selection is my \"current\" target? I would like to have different variables inside this function.

how can i retrieve which one of my selection is my "current" target? I would like to have different variables inside this function.

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

// if is $('#header a')  do this
// if is $('#nav a')  do that  开发者_开发技巧 

});


this will refer to the actual DOM element, and so you can check tagName or className, or look for $(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


Off-topic: I agree with Felix and melaos that if you're really doing things that different, refactoring into separate handlers (perhaps calling common functions) is probably the better way to go...


this refers to the current element in the matches collection for the selector/s. However if you need to process each element differently why do you want to bind the click event for the elements as a group (i.e using a single selector).

To manage the code in a better way I would use two bind calls like:

$("#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
}); 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号