Is there any way to delegate the event one in jQuery?

后端 未结 3 912
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 01:51

I would like to delegate the event one for the click. Does anyone know if it is possible to do it?

3条回答
  •  半阙折子戏
    2020-12-12 02:17

    Since this post is a few years old, I just wanted to provide a complete updated example for more contemporary readers (2015). The logic is no different from the other answers here, but jQuery's methods have evolved since 2011. Specifically:

    As of jQuery 1.7, .delegate() has been superseded by the .on() method.
    jQuery delegate()

    // define output element
    var $output = $('div#output');
    
    // attach delegated click handler
    $(document).on('click', 'button', function() {
      
      // define clicked element
      var $this=$(this);
      
      // if this element has already been clicked, abort
      if ($this.data('clicked')) {
        return false;
      }
       
      // perform click actions
      $output.append("clicked " + $this.html() + "
    "); // mark this element as clicked $this.data('clicked',true); });
    
    
    
    
    
    
    

提交回复
热议问题