用append添加的行如何动态删除?

代码如下:

$('.a2').click(function () {
                    var b3 = $('.b3').val();
                    var b4 = $('.b4').val();
          
                    var newRow = "<tr><td>" + b3 + "</td><td>" + b4 + "</td><td><button class='btn btn-danger" +
                        " btn-xs' id='a4'>删除</button></td></tr>";
                    $(".c1").append(newRow);
                });
                
                
                
                
                $('#a4').click(function () {
                alert('1');
                $(this).parents('tr').remove();
            })
                

clipboard.png
想实现动态删除添加的行 ,但是按照我上面的删除按钮没有反应,是因为button不能直接使用append添加到行里面吗?

阅读 8.4k
6 个回答
$('.a2').click(function () {
    var b3 = $('.b3').val();
    var b4 = $('.b4').val();
  
    var newRow = "<tr><td>" + b3 + "</td><td>" + b4 + "</td><td><button class='btn btn-danger" +
        " btn-xs' id='a4'>删除</button></td></tr>";
    $(".c1").append(newRow);
});        
                
$(document).on('click','#a4',function () {
    alert('1');
    $(this).parents('tr').remove();
})

你的行也是动态添加进去的吧 那么你的id就全部重复了
`<button onclick="remove(this)"></button>
function remove(th) {
$(th).parent().remove();
}`

照着手册开的脑洞,你试试:

$('.a2').click(function () {
    var b3 = $('.b3').val();
    var b4 = $('.b4').val();
    var newCol = [];
    newCol.push($('<td>').text(b3));
    newCol.push($('<td>').text(b4));
    newCol.push($('<button>', {
        'class': 'btn btn-danger btn-xs',
        text: '删除',
        click: function () {
            $(this).parents('tr').remove();
        }
    }).wrap('<td></td>'));
    $('<tr>').append(newCol).appendTo('.c1');
});

你的id也应该动态生成,或者直接根据tr在table中的索引进行删除

新手上路,请多包涵

var newRow = "<tr><td>" + b3 + "</td><td>" + b4 + "</td><td><button class='btn btn-danger" +" btn-xs' onclick="del(this)">删除</button></td></tr>";

function del(obj){

$(obj).parents('tr').remove();

}

给button设置一个类
然后用
$(".类名").click(function(){

$(this).parent('tr').remove();

});
试试看

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题