[英]javascript loop: variable equals the last iteration
用户单击添加更多链接后,下面的代码将添加元素。
当用户单击删除链接时,问题就来了。
我的代码中有类似的内容
<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”的最后一个值。 假设我要删除第三个元素,这时我单击删除链接时,它必须具有pass参数,例如remove(3)。 但是这里发生的是我单击的任何元素,好像它总是以这种方式传递参数remove(4)
那是因为您已经count
一个全局变量。
尝试.....onclick='remove("+count+")'....
对值进行“锁定”。
请尝试以下方法:
var printme = "<table id='table"+count+"'><tr><td><a href='#' onclick='remove("+count+")'>remove</a></td></tr></table";
还可以尝试以下行删除功能:
document.getElementById(""+tab+"").style.display = "none";
也许只是onclick ='remove('+ count +')'
你可以做类似的事情
<html>
<head>
<script type="text/javascript">
var count=1;
function addmore() {
var id = 'table' + count;
var table = document.createElement('table');
table.setAttribute('id', id);
var tr = document.createElement('tr');
var td = document.createElement('td');
var a = document.createElement('a');
a.setAttribute('href', '#');
a.appendChild(document.createTextNode('remove ' + id));
a.onclick = function() {
table.style.display = 'none';
document.body.removeChild(table);
};
td.appendChild(a);
tr.appendChild(td);
table.appendChild(tr);
document.body.appendChild(table);
count++;
}
</script>
</head>
<body>
<a href="#" onclick="addmore()">Add Table</a>
</body>
</html>
使用表引用和onclick这样定义,您不需要ID
先前的所有答案都是正确的,在调用remove时,onclick表示当前变量计数。
当您为表格生成文本时,请按原样使用count的值:
onclick='remove('+count+')...
您可以使用以下方法省略ID并进行总数计算:
onclick='remove(this.parentElement.parentElement.parentElement);'...
function remove(elementToRemove){
elementToRemove.parentElement.removeChild(elementToRemove);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.