JQuery event handler not firing after changing class

后端 未结 2 645
谎友^
谎友^ 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; }
    
    Click me

提交回复
热议问题