简体   繁体   中英

Remove class from td when the same class is clicked on

I have a bunch of <td> 's that have the class clickable

How can I remove the class clickable to no longer make them clickable? Here's what I have but it doesn't remove the class:

    $('td.clickable').click(function(){ 
        $(this).removeClass('clickable');
});

The code you have will certainly remove the class, however it doesn't remove the click event.

I'd suggest modifying your click event to use event delegation, like so:

$('table').on("click", ".clickable", function(){ 
    $(this).removeClass('clickable');
});

Example: https://jsfiddle.net/c6eda0kj/


Why event delegation is important:

Doing something like $('.clickable').click( ... ) creates a listener for every instance of clickable . If there are 100 .clickable td's, that's 100 listeners that you've just created. Regardless of whether or not you remove the class from those 100 elements, the event is already attached. In order to remove the event, you'll have to use unbind or off .

If you instead put the listener on the table as I have above, you have just one single event. When that event fires (the click of the table ), it checks to see if the clicked element matches the specified selector. By removing the class, it will then no longer trigger the event - no need for unbinding of any sort.

When you select the element, it adds the event. When the event is not removed because you remove the class. You have two options. Remove the click event. Other option is event delegation.

$('td.clickable').click(function(){ 
    $(this).removeClass('clickable').off("click");
});

or

$("table").on("click", 'td.clickable', function(){ 
    $(this).removeClass('clickable');
});

As @isherwood mentioned use off() instead of unbind()

here's an example:

 $('.clickable').click(function(){ console.log($(this).text()); $(this).off(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tr> <th>Company</th> <th>Contact</th> <th>Country</th> </tr> <tr> <td class="clickable">Alfreds Futterkiste</td> <td class="clickable">Maria Anders</td> <td class="clickable">Germany</td> </tr> <tr> <td class="clickable">Centro comercial Moctezuma</td> <td class="clickable">Francisco Chang</td> <td class="clickable">Mexico</td> </tr> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM