newbieee
newbieee

Reputation: 450

jquery bind click event in for loop

I'm trying to bind click event in for loop but any of the remove buttons remove only the last list item. Do you have any ideas why this happens?

for ( var key in editedPredef.predefinition) {
      var listItem = $("<li></li>").addClass("ui-widget-content");
      listItem.text("some text");
      var removeListItem = $("<span class=\"ui-icon ui-icon-closethick\"></span>");
      removeListItem.click(function() {
        listItem.remove();
      });
      listItem.append(removeListItem);
      containerElement.append(listItem);
    }

Upvotes: 2

Views: 1119

Answers (2)

T J
T J

Reputation: 43156

Change

removeListItem.click(function() {
    listItem.remove();
  });

to

removeListItem.click(function() {
    $(this).parent('li').remove();
  });

Side Note: this will bind an event handler to each element. You can make use of event delegation like Rajaprabhu mentioned in his answer. However, delegated event handlers will be slower than directly binder event handlers. So it's a matter of how many such elements you are likely to have in your application. If you're going for delegation, it'll be better to bind the event handler to an immediate parent element, which is not dynamically added, so that the response will be faster. For e.g., you can bind the event handler to the parent <ul> if it's not dynamically added and won't be removed from page like

$('ul').on('click','.ui-icon.ui-icon-closethick',function(){
 $(this).parent('li').remove();
});

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Don't write that inside a for loop just make use of event-delegation,

$(document).on('click','.ui-icon.ui-icon-closethick',function(){
  $(this).closest('li').remove();
});

And note that place this code outside of that for loop.

Upvotes: 5

Related Questions