简体   繁体   English

类名称更改后,将第二个单击事件附加到元素

[英]Attach second click-event to an element after class name has been changed

I have a div with a class name a . 我有一个类名为adiv I attach a click-event to this div like 我将点击事件附加到该div上,例如

$('.a').on('click',  function() {
    $(this).removeClass('a').addClass('b');
})

After this; 在这之后; element's class name changes from a to b . 元素的类名从a变为b I want to attach second click event on .b like 我想在.b上附加第二点击事件

$('.b').on('click', function() {
    $(this).removeClass('b').addClass('c');
})

First click event works fine however second one does not fire. 第一次点击事件可以正常运行,但是第二个不会触发。 See my JSfiddle. 参见我的JSfiddle。

Attach the click even to a higher element in the DOM - when you change the class, the event bubbling up will change, eg 将点击甚至附加到DOM中的较高元素-更改类时,冒泡的事件将发生变化,例如

$("body").on("click", ".b", function() {
    $(this).removeClass('b').addClass('c');
});

You can add the second event after the first one has fired: 您可以在第一个事件触发后添加第二个事件:

$('.a').on('click',  function() {
    $(this).removeClass('a').addClass('b');

    $('.b').on('click', function () { /* ... */ });
})

You're running the .b code at the beginning, when the element doesn't have class b. 当元素没有类b时,您在一开始就运行.b代码。 Try adding the new onClick handler in the code for your first onClick. 尝试在代码中为您的第一个onClick添加新的onClick处理程序。

Code: 码:

$('.a').on('click',  function() {
$(this).removeClass('a').addClass('b');
        $('.b').on('click', function() {
    $(this).removeClass('b').addClass('c');
    })
})

 $(".a").click(function() { $(this).removeClass("a").addClass("b"); $(".b").click(function() { $(this).removeClass("b").addClass("c"); }) }) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM