简体   繁体   中英

JQuery event handler not firing after changing class

I'm trying to have the span, on click, toggle its classes between .btn-warning and .btn-primary . However, my code only works for the first click. Every click thereafter doesn't work.

JavaScript

$(document).ready(function(){

    $('.btn-warning').on('click',function(){
        $(this).removeClass('btn-warning').addClass('btn-primary');
    });
    $('.btn-primary').on('click',function(){
        $(this).removeClass('btn-primary').addClass('btn-warning');
    });
});

HTML

<span class="btn btn-warning" >Click me</span>

Changing the class does not magically add the events that were previously added. You either need to unbind/bind the events once again, or use a generic onclick handler that knows how to handle it, or use event delegation.

All that code could be reduced to:

 $(".btn").on("click", function() { $(this).toggleClass('btn-warning').toggleClass('btn-primary'); }); 
 .btn-primary { background-color: blue; } .btn-warning { background-color: yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <span class="btn btn-warning" >Click me</span> 

You need to use event delegation method because you're binding event to dynamically added class element:

$(document).ready(function(){

    $(document).on('click','.btn-warning',function(){
        $(this).removeClass('btn-warning').addClass('btn-primary');
    });
    $(document).on('click','.btn-primary',function(){
        $(this).removeClass('btn-primary').addClass('btn-warning');
    });
});

Simply you may do like this:

$(document).on("click",".btn", function() {
    $(this).toggleClass('btn-warning btn-primary');
});

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