开发者

Late binding in jquery?

开发者 https://www.devze.com 2023-03-20 02:10 出处:网络
There is a table which has one row: <table> <tr><td><span class=\"removeItem\"></span></td></tr>

There is a table which has one row:

<table>
  <tr><td><span class="removeItem"></span></td></tr>
</table>

I use this to bind a function to a class:

  $('.removeItem').bind('click', function() {
    $(this).parent().remove();
    return false;
  });

later, I add rows with the same class name (.removeItem) into the table:

var newRow = '<tr><td><span class="removeItem"></span></td><开发者_StackOverflow中文版/tr>';
$(table).append(newRow);

When I click on the first row item, it is removed. The dynamically added one is not.

Why is this?


Use event delegation by placing a handler on the table with the delegate()[docs] method:

$('table').delegate('.removeItem','click', function() {
    $(this).closest('tr').remove();
    return false;
});

...you'll probably want to place an ID on the table in order to narrow your selection.

Now click events that bubble up to the table will invoke the handler if the item clicked matches the ".removeItem" selector.

I also changed it to use the closest()[docs] method to get the nearest <tr> ancestor.


Working example: http://jsfiddle.net/UxbcN/

This is generally preferred over .live() because it only needs to run the selector for clicks inside the table instead of all clicks in the entire document.


You'll need to use the live function. This will bind the click event to future elements that match the selector.

$('.removeItem').live('click', function() {
    $(this).parent().remove();
    return false;
});


bind() by design only binds handlers to the results of $("mySelector") at that precise moment. You have two alternatives in your described scenario:

  1. Call bind() on your new rows after you create them.
  2. Call live() which binds against all current and future elements that match the selector. (See documentation for live).
0

精彩评论

暂无评论...
验证码 换一张
取 消