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

后端 未结 7 653
时光说笑
时光说笑 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:29
    $(document).on('click', '.clickable', function() {
      $(this).removeClass('clickable');
      $(this).addClass('not-clickable');
      alert('Clicked!');
    });
    
    0 讨论(0)
  • 2020-12-03 05:31

    When you attach an event handler to a DOM element, it stays intact. The class is just a way to reference the element, and changing the class will not unbind the event handlers, for that you will have to manually unbind the handler, and if using jQuery 1.7+ on() and off() is the way to go :

    $('.clickable').on('click', function() {
      $(this).removeClass('clickable').addClass('not-clickable').off('click');
    });
    

    this would make the element clickable only once, and you could just use the built in one() function instead, as that will unbind the handler automagically after the first click :

    $('.clickable').one('click', function() {
      $(this).removeClass('clickable').addClass('not-clickable');
    });
    
    0 讨论(0)
  • 2020-12-03 05:34

    unbind click event - like $(this).unbind('click');' Try this

    $('.clickable').click(function() {
      $(this).removeClass('clickable');
      $(this).addClass('not-clickable');
      $(this).unbind('click');'
    });
    
    0 讨论(0)
  • 2020-12-03 05:38

    If you want to call click event only once use jQuery one function to bind events it will destroy itself.

    $('.clickable').one('click',function() {
       $(this).removeClass('clickable');//remove the class
       $(this).addClass('not-clickable');
       alert('Clicked!');
    });
    
    0 讨论(0)
  • 2020-12-03 05:41
    $('.clickable').live('click',function() {
      $(this).removeClass('clickable');//remove the class
      $(this).unbind('click');//to remove the click event
      $(this).addClass('not-clickable');
      alert('Clicked!');
    });
    
    0 讨论(0)
  • 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!');
    });
    
    0 讨论(0)
提交回复
热议问题