jQuery追加和绑定点击事件使用on [英] jQuery append and binding click event using on

查看:93
本文介绍了jQuery追加和绑定点击事件使用on的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个带有按钮的表行,单击该按钮会创建一个新的表行。新行也有相同的添加行按钮,我希望能够单击该按钮添加另一行。但我似乎无法将click事件绑定到click事件中附加的元素。我确信我正在使用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. 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(简化)html

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(简体)javascript

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

提前致谢。

推荐答案

您必须将处理程序绑定到非动态的元素。您正在尝试绑定到 td ,这在您执行绑定时不存在。您可以改为绑定到表格:

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) {   

这篇关于jQuery追加和绑定点击事件使用on的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆