Reputation: 236
I'm a beginner in jquery or javascript. And I'm wondering is there anyway to write a click event for multiple elements and multiple function.
For example, I have a lot of buttons that will execute different function when clicked. Is there anyway to include all the function in 1 click event? Like "document on click", "button1" will do "function ...", "button2" will do "function ...".
More like a switch case styled ??
Upvotes: 0
Views: 59
Reputation: 1074038
You could do that, yes, but it wouldn't be best practice. It would look something like this:
$(document).on("click", "button", function() {
switch (this.id) { // (Or whatever you want to use to differentiate the buttons)
case "button1":
// Do button1's stuff
// ...
break;
case "button2":
// Do button2's stuff
// ...
break;
// ...and so on...
}
});
But it's much better to use separate handlers. They can still be delegated if you're adding and removing buttons dynamically:
$(document)
.on("click", "#button1", function() { // Again, it doesn't have to be an id...
// button1's stuff here
})
.on("click", "#button2", function() { // ...just whatever differentiates the buttons
// button2's stuff here
});
Upvotes: 1