weixin_33736832 2013-02-24 14:38 采纳率: 0%
浏览 11

开启/关闭javascript

I am trying to make a swith on / off javascript, but I have a problem: I click always comes in my first class despite my class change.

I have always the same result : on->on or off->off. I check in Firebug my html is changed correctly...

Here my simplified code :

$('.off').on('click', function(e) {
    e.stopPropagation();
    e.preventDefault();

    alert('off');

    $(this).removeClass('off');
    $(this).addClass('on');
});

$('.on').on('click', function(e) {
    e.stopPropagation();
    e.preventDefault();

    alert('on');

    $(this).removeClass('on');
    $(this).addClass('off');
});

if anyone has a suggestion, I would be very grateful !!

  • 写回答

4条回答 默认 最新

  • weixin_33694620 2013-02-24 14:44
    关注

    The event handlers are bound on pageload, so changing the class won't change the event handlers, as they are attach to whatever elements existed at the time of binding. To attach them to future elements, i.e. when you change the classes, you'll need delegated event handlers, but an easier solution in my opinion is to just toggle the classes or use a flag:

    $('.off').on('click', function(e) {
        e.preventDefault();
        var state = $(this).is('.off') ? 'on' : 'off';
    
        alert(state);
    
        $(this).toggleClass('off on');
    });
    

    FIDDLE

    It can be confusing, but even if you remove the .off class, the event handler is still bound to the same element, as it had the .off class at the time of binding!

    评论

报告相同问题?