简体   繁体   English

jQuery附加并使用on绑定click事件

[英]jQuery append and binding click event using on

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. 但是我似乎无法使click事件绑定到click事件中附加的元素。 I am sure I am using "on" incorrectly but I can't seem to figure out how to do this. 我确定我使用了“ on”错误,但似乎无法弄清楚该怎么做。

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

my (simplified) html 我的(简体)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 我的(简体)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. 提前致谢。

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. 您正在尝试绑定到td ,绑定时不存在。 You can bind to the table instead: 您可以绑定到表:

http://jsfiddle.net/TMvN6/ http://jsfiddle.net/TMvN6/

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

Working Demo http://jsfiddle.net/Z5Vvc/ 工作演示 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. 您可以尝试将其简单地附加到$(document).on(现在添加“ +”,依此类推。如果您热衷于阅读,则很容易阅读Doc链接。

API doc: .on - http://api.jquery.com/on/ API文档: .on - http : .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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM