JQuery event handler not firing after changing class

后端 未结 2 630
谎友^
谎友^ 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: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');
    });
    

提交回复
热议问题