JQuery event handler not firing after changing class

后端 未结 2 610
谎友^
谎友^ 2021-01-26 04:42

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. Ever

相关标签:
2条回答
  • 2021-01-26 05:18

    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>

    0 讨论(0)
  • 2021-01-26 05:25

    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');
    });
    
    0 讨论(0)
提交回复
热议问题