简体   繁体   中英

Bind click event function to a dynamically-created element

I'm creating elements using an Ajax request. I want to bind a function to each element to run in its click event. How can I do this? Here is my code where I generate the elements.

ajaxCall("/getItems","POST",data,function(result){
  var element = $('.item').first();
  $('#item-list-section').empty();
  for(var i = 0; i < result.items.length; i++){
    var clone = element.clone();
    clone.attr("id", result.items[i].itemId);
    clone.find('.item-price').html("<h4>25</h4>");
    if(result.items[i].itemName.length > 20){
      clone.find('.item-name').css('overflow','hidden');
      clone.attr('title', result.items[i].itemName )
    }
    clone.find('.item-name').html("<h4>"+ result.items[i].itemName + "</h4>");
    //clone.mousedown(onItemClick(clone));
    clone.draggable({
      revert : false,
      zIndex: 1,
      containment: "window",
      opacity: 0.5,
      cursor: "move",
      helper: function() { return $(this).clone().appendTo('body').show(); }
    });
    $('#item-list-section').append(clone);
  }
});

Need to use event delegation Which attaches the events to the elements using the concept of event bubbling...

$(staticContainer).on("click", element , function(event){
  // Code here
});

staticContainer -- The element which is always present in the DOM. The closer it is to the dynamically created elements the better.

element - Dynamically created entity to which you want to attach the event

$(clone).on("click", function(event){
  alert($(this).attr('id'));
});

Check this to find out if it alerts the id.

In each loop of elements

$(clone).each(function(index, value) { 
$(value).on("click", function(event){
  alert($(this).text());
});
}
$(clone).bind("click",function(event){
// your code
});

Please try this.

$(document).on("click",value, function(event){
  alert($(this).text());
});

One solution is using event delegation with .on() method:

$('#item-list-section').on('click', '.item', function () {
    // do something
});

Another solution is clone your element with events, just pass true to your .clone() method:

var clone = element.clone(true);
  • Note that this will work if your var element = $('.item').first(); is static on the page.

References:

  • .clone() - jQuery API Documentation
  • .on() - jQuery API Documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM