javascript - 行删除不起作用

标签 javascript jquery html

在我的代码中,删除第一行有效,但后续行无效

html代码:

<table class="table table-striped table-bordered table-hover table-condensed tableSiteUser">
    <thead>
        <tr>
            <th>#</th>
            <th>User</th>
            <th>Channel</th>
            <th>Action</th>
        </tr>
        <tr>
            <td contentEditable="true">1</td>
            <td contentEditable="true">www.google.com</td>
            <td contentEditable="true">channel-1</td>
            <td contentEditable="true"><span class="glyphicon glyphicon-trash form-control row-remover">delete</span>
            </td>
        </tr>
    </thead>
    <tbody id="site-table-body"></tbody>
</table>

javascript代码:

$('.table tbody').append('<tr><td contenteditable="true">1</td><td contenteditable="true">1</td><td contenteditable="true">1</td><td contenteditable="true"><span class="glyphicon glyphicon-trash form-control row-remover">del</span></td></tr>');

$('.table').on('keydown', 'td:last-child', function (e) {
    var keyCode = e.keyCode || e.which;

    if (keyCode == 9) {
        $('tbody').append('<tr><td contenteditable="true">2</td><td contenteditable="true">2</td><td contenteditable="true">2</td><td contenteditable="true"><span class="glyphicon glyphicon-trash form-control row-remover">del</span></td></tr>');
    }
});

$('span.glyphicon-trash').on('click', function () {
    $(this).closest('tr').remove();
});

fiddle 链接:http://jsfiddle.net/vasantharaj/vkfr2fbo/1/

最佳答案

当您动态创建元素时。您需要使用 Event Delegation使用 .on()委托(delegate)事件方法。

使用

$('.table tbody').on('click', 'span.glyphicon-trash', function() {
    $(this).closest('tr').remove();
});

DEMO

关于javascript - 行删除不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30389565/

相关文章:

javascript - 在具有全高页面的javascript中获取滚动事件

html - 带有来自 Amazon S3 的图像的 Img 标签不起作用

javascript - jquery 中 $.get 之后丢失选择器

javascript - 无法使用 columnFilter 重新初始化 DataTable 错误

javascript - 如何将 Instagram 图片整合到 slider 中?

javascript - jQuery Boilerplate - 无法访问 "this"范围

javascript - 延迟加载某个 css 背景图片

javascript - 有没有办法在 HTML/CSS 中为整个窗口/页面/主体更改短时间光标

javascript - CoffeeScript:像 Rickshaw Prototype 示例中那样扩展 super 方法

javascript - 通过 jQuery 更改表单上的操作后,GET 变量消失。