如何防止表对同一条记录发出两次警报

How to prevent the table from alerting the same record twice?

本文关键字:两次 何防止 记录 一条      更新时间:2023-09-26

我有一个在JavaScript中创建的表。单击按钮时,应该显示该行的行id,但单击按钮时,行id会收到两次警报。

下面是我的JavaScript代码:

newContent += Hesto.Html.CreateTD('<button type="button" value="Print" class="btnprint" onclick="test(this)">', null);
function test() {
    $("button").click(function () {
        var row  = $(this).parents('tr').attr('id');
        var rowtext = $(this).closest('tr').text();
        alert(row);
    });
}

它多次发出警报的原因是因为您多次委托同一事件,使用事件委托,并删除元素

上的onclick="test(this)"
$(document).on('click','.btnprint',function(){
 var row  = $(this).parents('tr').attr('id');
 var rowtext = $(this).closest('tr').text();
 alert(row);
});

在你的例子中,你可以调用按钮两次1)onclick="test(this)",2)button click

 function test() {                   
                    var row  = $(this).parents('tr').attr('id');
                    var rowtext = $(this).closest('tr').text();
                    alert(row);
                 }

否则你可以使用委托。@Anton张贴方法

$(document).on('click','.btnprint',function(){
 var row  = $(this).parents('tr').attr('id');
 var rowtext = $(this).closest('tr').text();
 alert(row);
});
function test() {
    $(document).on('click', '.btnprint', function () {
        var row = $(this).parents('tr').attr('id');
        var rowtext = $(this).closest('tr').text();
        alert(rowtext);
    });
}