Question

Say I delegate an event handler to elements of a class ".btn," and each element with a class ".btn" would have another class associated with it indicating what kind of button it is. For example:

<div class=".btn show">text</div>

Would be a button that shows things.

If I have a million of these cases, would this be good practice?

$(document).ready(function() {
    $('table').on('click', '.btn', function() {
        if ($(this).hasClass('show')) {
             show something ... 
        } else if ($(this).hasClass('submit')) {
             submit something ...
        } else if ($(this).hasClass('foo')) {
             do something ...
        }

That is, should I have different event handlers for each kind of button (every one of which does something different):

 $('.btn .show').click(function() {
     show something ...
 });

Or should I check the class associated with hasClass(), using a chain of if else statements? Why?

Was it helpful?

Solution

I think you should use the if..else if chains, because the it will make your code easy to understand and I it should be faster as you are calling that on click event of current element

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top