jQuery append and binding click event using on

穿精又带淫゛_ 提交于 2019-12-11 02:17:15

问题


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


来源:https://stackoverflow.com/questions/19282406/jquery-append-and-binding-click-event-using-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!