jQuery append and binding click event using on

2019-07-17 05:14发布

问题:

I am attempting to create a table row with a button in it that when clicked creates a new table row. The new row also has the same "add line" button on it and I would like to be able to click that button to add another row. But I cannot seem to get the click event to bind to an element that is appended within the click event. I am sure I am using "on" incorrectly but I can't seem to figure out how to do this.

http://jsfiddle.net/vivojack/WkfvC/2/

my (simplified) html

<table id="ct">
    <tbody>
    <tr id="list_items_11" class="list_item">
        <td>This Line</td>
        <td><input type="button" name="addNewArea" class="addNewArea button" value="+"></td>
      </tr>
   </tbody>
</table>

my (simplified) javascript

$('#ct tbody tr td').on('click', '.addNewArea', function(event) {   
    var areaCount = $('#ct tbody tr').length;
    var newAreaLine = '<tr id="list_items_' + areaCount + '" class="list_item"><td>New Line</td><td><input type="button" name="addNewArea" class="addNewArea button" value="+" /></td></tr>';
    $(newAreaLine).appendTo('#ct tbody');
    $(this).remove();
});

Thanks in advance.

回答1:

You have to bind the handler to an element that isn't dynamic. You're attempting to bind to the td, which doesn't exist when you do the binding. You can bind to the table instead:

http://jsfiddle.net/TMvN6/

$('#ct').on('click', '.addNewArea', function(event) {   


回答2:

Working Demo http://jsfiddle.net/Z5Vvc/

You can try and simply attach it to the $(document).on( it now adds the "+" so on and so forth. Doc link is pretty saweet to read if you keen.

API doc: .on - http://api.jquery.com/on/

Hope this help your need :)

code

$(document).on('click', '.addNewArea', function(event) {    
    var areaCount = $('#ct tbody tr').length;
    var newAreaLine = '<tr id="list_items_' + areaCount + '" class="list_item"><td>New Line</td><td><input type="button" name="addNewArea" class="addNewArea button" value="+" /></td></tr>';
    $(newAreaLine).appendTo('#ct tbody');
    $(this).remove();
});