我已经创建了一个非常基本的表格和复选框布局。我在一个表中有八个文本框和八行。我只是尝试在复选框选中时添加行并在取消选中时删除。
因此,我使用了两个相同的函数。
function show(input){
var tbody = document.getElementById("tbody");
if(document.contains(document.getElementById("tr"+input)))
{
hide('tr'+input);
}
if(!document.contains(document.getElementById("tr"+input)))
{
tbody.appendChild(getRow(input));
}
}
function hide(input){
if(document.contains(document.getElementById(input)))
{
var child = document.getElementById(input);
child.parentNode.removeChild(child);
child.parentNode.removeChild(child);
}
}
在隐藏函数中,如果我只使用一个 removeChild 语句,它不起作用。使用两个时,控制台会报告错误,但它运行良好。
如果有人知道原因,请告诉我,因为在代码中留下错误是不道德的。
编辑 #1:JsFiddle
最佳答案
你的问题是这个函数:
function show(input) {
var tbody = document.getElementById("tbody");
if (document.contains(document.getElementById("tr" + input))) {
hide('tr' + input);
}
if (!document.contains(document.getElementById("tr" + input))) {
tbody.appendChild(getRow(input));
}
}
首先,您检查该节点是否存在,如果存在,则将其隐藏。接下来,您始终检查节点是否不存在,如果存在,则添加它。当节点刚刚被隐藏时,第二次检查将为 true
(因为您刚刚删除了该节点)并且该节点会再次添加回来。
所以重写为:
function show(input) {
var tbody = document.getElementById("tbody");
if (document.contains(document.getElementById("tr" + input))) {
hide('tr' + input);
} else if (!document.contains(document.getElementById("tr" + input))) {
tbody.appendChild(getRow(input));
}
}
关于javascript - node.removeChild(child) 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20139602/