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!

    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址