行删除不起作用

Row delete does not work

本文关键字:不起作用 删除      更新时间:2023-09-26

在我的代码中删除第一行工作,但以下行不工作

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

小提琴链接:http://jsfiddle.net/vasantharaj/vkfr2fbo/1/

在动态创建元素时。您需要使用.on()委托事件方法来使用事件委托。

使用

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

<td contentEditable="true">
<span class="glyphicon glyphicon-trash form-control row-remover" onclick="js : return deleterow(this);">delete</span>
</td>
<script>
function deleterow(i){
  $(i).closest('tr').remove();
}
</script>
its should be work

这是为未来的观众提供的香草javascript版本

(演示)

(function () {
    "use strict";
    var tbodies = document.getElementsByTagName('tbody'), tbody;
    for (var i = 0; tbody = tbodies[i]; i++) {
        tbody.addEventListener('click', function (e) {
            if (e.target.className.indexOf('row-remover') >= 0) {
                e.target.parentElement.parentElement.remove();
            }
        }, false);
    }
})();