如何在动态生成的HTML表中停止递归

How to stop recursion in dynamically generated HTML table

本文关键字:递归 HTML 动态      更新时间:2023-09-26

有关问题的工作示例,请参阅jsfiddle。

http://jsfiddle.net/grdhog/Wng5a/5/

当我向表中添加一行时。我首先通过ajax将其发送到服务器,然后通过ajax json调用完全重建表。当我删除一行时,我首先通过ajax将其发送到服务器,然后通过ajax json调用完全重建表。

删除是递归的-请参阅控制台输出

单击几行以"删除"它们,您将看到递归。这个简化的例子实际上并没有添加或删除行,但希望您能理解。你能解释一下我为什么有这个问题以及如何解决吗。我怀疑我从delete click调用get_rows()是问题的一部分。

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body><p>Turn on the Javascript console to see output:</p>
    <button id="add">add new row</button>
    <table id="rows">
    </table>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
$(document).ready(function() { 
    get_rows();
    $('#add').click(function() {  
        // ajax call to server to add row
        console.log("add row");
        get_rows();
        return false;
    });
    function get_rows(){
        console.log("inside get_rows!");
        $("#rows").empty();
        // ajax call to return all rows
        for (i=0; i < 5;i++){
            var item = '<tr><td id="' + i + '" class="del_row">delete row ' + i + ' by clicking me!</td></tr>';
            $("#rows").append(item);             
        }
        $(document).on("click", ".del_row", function(){
            id = $(this).prop('id');
            console.log("delete row " + id);
            // ajax call to delete on server
            get_rows();                            
        });                                   
    }
}); // end ready

    </script>
  </body>
</html>

您必须将.on调用移出get_rows函数。因为除此之外,每次调用get_rows都会添加一个新的侦听器。

function get_rows(){
    console.log("inside get_rows!");
    $("#rows").empty();
    // ajax call to return all rows
    for (i=0; i < 5;i++){
        var item = '<tr><td id="' + i + '" class="del_row">delete row ' + i + ' by clicking me!</td></tr>';
        $("#rows").append(item);             
    }                                  
}
 $(document).on("click", ".del_row", function(){
        id = $(this).prop('id');
        console.log("delete row " + id);
        // ajax call to delete on server
        get_rows();                            
 });

http://jsfiddle.net/Wng5a/6/

id属性不能是数字,您可以在这里阅读更多信息HTML中id属性的有效值是什么?

当然,这不能回答你的问题,但你可以防止其他人在未来出现问题。