【问题标题】:How to stop recursion in dynamically generated HTML table如何在动态生成的 HTML 表中停止递归
【发布时间】:2014-06-12 02:15:13
【问题描述】:

有关问题的工作示例,请参阅 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>

【问题讨论】:

标签: javascript jquery ajax json recursion


【解决方案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/

【讨论】:

  • 好吧,作为一个新手,我觉得每次删除和替换表行时我都​​需要“重新连接”del_row 事件侦听器。 $(document).on("click.. 继续工作。谢谢。
【解决方案2】:

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

这当然不能回答您的问题,但您可以防止将来出现其他问题。

【讨论】:

    猜你喜欢
    • 2021-12-24
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 2013-05-18
    • 2012-05-07
    • 2019-03-10
    相关资源
    最近更新 更多