请参阅 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>
最佳答案
您必须将 .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();
});
关于javascript - 如何在动态生成的 HTML 表中停止递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23308805/