jQuery.on函数无法正常工作

时间:2013-02-15 06:29:00

标签: javascript jquery

我正在使用jQuery 1.9.1,我需要对动态添加的td执行操作。我试图使用jQyuery.on函数,但我的代码没有被调用。请帮忙!这是我的代码

HTML

<div>First Name:
    <input type="text" name="txtFName" id="txtFName" />
    <br/>Last Name:
    <input type="text" name="txtLName" id="txtLName" />
    <br/>
    <input type="button" value="Add User" id="btnAdd" />
</div>
<br/>
<div>Users
    <table id="tblusers">
        <thead>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th></th>
            </tr>
        </thead>
        <tbody id="tbUsers"></tbody>
    </table>
    <br/>
    <input type="button" value="Save Users" />
</div>

的Javascript

$(document).ready(function () {
    $('#btnAdd').click(function () {
        var content = "";
        var fName = $('#txtFName').val();
        var lName = $('#txtLName').val(); ;
        content = "<tr><td>" + fName + "</td><td>" + lName + "</td><td class=\"clremove\">Delete</td></tr>";
        $('#tbUsers').append(content);
    });

    $('.clremove').on('click', function () {
        $('#tbUsers tr').remove($(this).closest('tr'));
    });
});

这是我的Fiddler

2 个答案:

答案 0 :(得分:5)

当你致电.clremove时,

.on不存在,所以没有任何约束。您想使用事件委派:

$("#tbUsers").on('click', '.clremove', function () {
    $("#tbUsers tr").remove($(this).closest('tr'));
});

答案 1 :(得分:1)

由于您的clremove是动态添加的,$('.clremove').on('click'..事件不会触发(docuemnt中一次不存在)..您可以使用on()委托事件。< / p>

$('#tbUsers').on('click','.clremove' function () {
    $('#tbUsers tr').remove($(this).closest('tr'));
});

如果您想了解有关jquery.on及其直接和委派活动的更多信息,可以浏览link

相关问题