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

时间:2014-04-26 09:02:58

标签: javascript jquery ajax json recursion

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

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

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

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

单击几行以“删除”它们,您将看到递归。 这个简化的示例实际上并没有添加或删除行,但希望您能得到这个想法。 你能解释一下为什么我有这个问题以及如何解决它。 我怀疑我从删除点击中调用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>

2 个答案:

答案 0 :(得分:1)

id属性不能是一个数字,你可以在这里阅读更多What are valid values for the id attribute in HTML?

当然,这不会回答你的问题,但你可以在将来防止其他问题。

答案 1 :(得分:1)

您必须将.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/