更改类后无法触发jQuery事件处理程序 [英] JQuery event handler not firing after changing class

查看:67
本文介绍了更改类后无法触发jQuery事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在单击时使跨度在.btn-warning.btn-primary之间切换.但是,我的代码仅适用于首次点击.此后的每次点击都无效.

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>

推荐答案

更改类不会神奇地添加以前添加的事件.您要么需要再次取消绑定/绑定事件,要么使用知道如何处理事件的通用onclick处理程序,或者使用事件委托.

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>

这篇关于更改类后无法触发jQuery事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆