0

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);
  }
});

6 Answers 6

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Check this to find out if it alerts the id.

Comments

0

In each loop of elements

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

Comments

0
$(clone).bind("click",function(event){
// your code
});

Please try this.

1 Comment

on is the preferred method.
0
$(document).on("click",value, function(event){
  alert($(this).text());
});

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.