Here's a very small issue that I was unable to figure out. I'm sure someone can answer in no time:
Having multiple selectors like
$('a.button, span.xyz, a.another').click(function(e) {
var clicked_element = ???;
});
, how can I figure out which selector was actually clicked? I need to use it like $(clicked_element)...
.
Thanks.
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");
}
});
Edited:
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
This would be a better approach
$("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) { ... });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With