Reputation: 90
I'm here for a short question which is pretty simple (I think). Sorry if it's a duplicate but I can't find this question elsewhere.
I just want to know which element was selected by the selector when you select multiple elements.
For exemple :
$('body').on('click', '.add, .remove', function() {
// if $(this) is a .add element, do something
// if $(this) is a .remove element, do another thing
}
I can obviously create two functions, but the two will be very long and very similar so I don't want to.
I tested $(this).is($('.add))
, $(this).hasClass('add')
and they both didn't work.
I also tried something like :
$('body').on('click', '.add', foo('add'));
$('body').on('click', '.remove', foo('remove'));
function foo(which) {
if (which == 'add')
// do something
else
// do something
}
but I faced strange behaviours (the function is called while I don't call it etc). I think I don't fully understand how defined functions work in Javascript.
Can you help me please ?
Upvotes: 0
Views: 136
Reputation: 2289
.on()
accepts a reference to a callback function, you are passing in an invocation:
$foo.on('click', bar); // bar is called on click
$foo.on('click', bar()); // the *result* of calling bar is called on click
The second approach isn't wrong in any way, as bar()
could be a function that returns a function (making this (function_returned_from_bar)()
, it's just not what you need. Your approach to filtering the selectors from the body is fine and legit, so I've built on it in my proposed solution. You can read about that event.data
-stuff going on in the docs.
$('body').on('click', '.add', {method: 'add'}, foo);
$('body').on('click', '.remove', {method: 'remove'}, foo);
function foo(event) {
// could also use switch/case
if (event.data.method === 'add') {
$('.log').append('Added<br>');
} else {
$('.log').append('Removed<br>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">
Add
</button>
<button class="remove">
Remove
</button>
<div class="log"></div>
Upvotes: 1
Reputation: 376
You are selecting add and remove in a strange way, I think i may cause misbehavior try this instead:
$('.add').on('click', foo('add'));
$('.remove').on('click', foo('remove'));
function foo(which) {
if (which == 'add')
// do something
else
// do something else
}
Upvotes: -1
Reputation: 3819
I think you could modify your last approach... the trouble is your are invoking the function when you should just be giving a function name. You can fix it like this:
$('body').on('click', '.add', function() {foo('add');});
$('body').on('click', '.remove', function() {foo('remove');});
function foo(which) {
if (which == 'add')
// do something
else
// do something
}
Upvotes: 2