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
});
精彩评论