我有这个代码:
function displayMenu (newGal, newSub) {
curGal = newGal;
curSub = newSub;
if (curGal == null) {
curGal = "main";
};
arrayL = curGal.length;
if (curImg == null) {
curImg = 0;
};
if (curSub == null) {
curSub = 0;
};
prevImg = curImg - 1;
if (prevImg == null || prevImg < 0) {
prevImg = arrayL;
};
nextImg = curImg + 1;
document.getElementById('img1').style.display = "none";
};
无论它给我什么,style
属性都是 null
。该代码已从以前的代码中大量删除;这是 for
循环的一部分,该循环应该使用 i
来定位 "img"+ i
以选择 div
的 id
为 img0
-9
,然后我将其分解并尝试手动定位每个 img0
-9
有一个单独的行,它只是不断中断。是的,img0
-9
div 在 HTML 中。原始的 for
循环看起来像这样:
for (i = 0; i < array.L; i++) {
var tempButton = "img" + i;
document.getElementById(tempButton).style.display = "none";
};
为什么 style
属性为 null
,我该如何解决?
最佳答案
window.onload = displayMenu('main', 0);
这是你的问题。改用这个:
window.onload = function() {displayMenu('main', 0);}
在您的代码中,displayMenu
被调用,然后该调用的返回值 被分配给 window.onload
。这会失败,因为您在添加 imgX
元素之前分配了 window.onload
。
在解决方案中,您改为将函数文字分配给 window.onload
,它在调用时运行 displayMenu
。它现在可以工作了,因为元素已被放置在页面上。
关于javascript - `style` 属性是元素上的 `null`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11379951/