jQuery click() still being triggered after .clickable class is removed

后端 未结 7 652
时光说笑
时光说笑 2020-12-03 05:29

I\'ve got a click event assigned to a div of a particular class. When the click occurs, the class is removed from the div. However, you can still click the div and the

7条回答
  •  有刺的猬
    2020-12-03 05:44

    You can use this

    $(document.body).delegate('.clickable', 'click', function(e){
        $(this).removeClass('clickable');
        alert('Clicked!');
    });
    

    From jQuery version 1.7 delegate() is superseded by the on()

    $(document.body).on('click', '.clickable', function(e){
        $(this).removeClass('clickable');
        alert('Clicked!');
    });
    

    Or

    $('.clickable').on('click', function(e){
        $(this).removeClass('clickable').off('click');
        alert('Clicked!');
    });
    

    Also you can use method one() - it's equal to bind, but occurs once

    $('.clickable').one('click', function(e){
        alert('Clicked!');
    });
    

提交回复
热议问题