Is there a way to delegate an event in jQuery?

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

+2
source share
3 answers

I'm going to assume that you want the event to fire only once, so that the consistent PER element, and not completely shut off on the first click.

I would do it like this:

$('#container').delegate('.children', 'click', function() {
  if($(this).data('clicked')) {
      return;
  }

  // ... your code here ...


  $(this).data('clicked', true);

});

This will only fire once for each item. Technically, it works every time, but is flagged on the first click, so the code will not be executed again.

.one() , .one() , , . , , / . .delegate(), SINGLE.

, , , .one() ( ).

+8

, (2015). , jQuery 2011 . :

jQuery 1.7,.delegate() .on().
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() + "<br />");
 
  // mark this element as clicked
  $this.data('clicked',true);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>One</button>
<button>Two</button>
<button>Three</button>

<div id="output"></div>
Hide result
+2

, , :

<script>
  $(document).ready(function(){
    $("#container").delegate('.clickers', 'click', function(){
      if($(this).data("clicked")==null){
        $(this).data("clicked", "true");
        $("#container").append($(this).html());
      }
    });
  });
</script>
<div class="clickers" clicked="false"></div>
<div class="clickers" clicked="false"></div>

: , DOM w3c.

+1

All Articles