我在这行
上得到一个空错误document.getElementById("Attachment" + x).style.display = "none";
我真的不想写出5次。如果我这样做,该线路确实有效。
document.getElementById("Attachment1").style.display = "none";
我在这里缺少什么?为了保持这个简短,我只包括了出错误的循环。
for (x = 0; x < 5; x++)
{
if(showHideArray[x] > 0)
{
document.getElementById("Attachment" + x).style.display = "none";
}
else {
document.getElementById("Attachment" + x + "If").style.display = "none";
}
}
答案 0 :(得分:3)
您可能没有ID为Attachment0
的元素。
答案 1 :(得分:0)
如果没有具有给定id的元素,则此函数返回null。所以,如果我是你,我会打印document.getElementById("Attachment" + x).style.display = "none";
告诉我们它输出的内容。但是一个可行的解决方案是:
for (x = 0; x < 5; x++)
{
if(showHideArray[x] > 0)
{
var y = "Attachment" + x;
document.getElementById(y).style.display = "none";
}
else {
var z = "Attachment" + x + "If";
document.getElementById(z).style.display = "none";
}
}
我会尝试这两件事。
答案 2 :(得分:0)
您正在尝试访问style
的属性null
,这会引发错误。在尝试访问属性之前检查元素是否存在。
for (x = 0; x < 5; x++) {
var elem = document.getElementById("Attachment" + x + (showHideArray[x] > 0 ? "If" : "" ) );
if( elem ) {
elem.style.display = "none";
}
}