一旦用户单击addmore链接,下面的代码将添加元素。
当用户单击删除链接时就会出现问题。
我的代码中有类似的内容
<script language="JavaScript">
var count=1;
function addmore() {
alert(count);
var printme = "<table id='table"+count+"'><tr><td><a href='#' onclick='remove(count)'>remove</a></td></tr></table";
//(other code here)...
count++;
}
function remove(y) {
alert(y)
var tab = 'table'+y;
document.getElementById(tab).style.display = "none";
}
</script>
我在这里使用了警报,这样我就可以轻松监控它给出的计数值。
这里发生的情况是“y”的值(在删除函数上)始终相同,这是循环中 count 的最后一个值。
例如,我单击链接 addmore 3 次,因此我的“count=4”的最后一个值。 假设我想删除第三个元素,此时当我单击删除链接时,它必须具有像这样的删除(3)这样的传递参数。但这里发生的是我点击的任何元素,它似乎总是以这种方式传递参数remove(4)
最佳答案
那是因为您将 count
作为全局变量。
尝试 .....onclick='remove("+count+")'....
来“锁定”该值。
关于JavaScript循环: variable equals the last iteration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13736957/