javascript - `style` 属性是元素上的 `null`

标签 javascript

我有这个代码:

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 以选择 dividimg0-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/

相关文章:

javascript - INVALID_STATE_ERR : DOM Exception 11

javascript - Apostrope CMS 中的文章作者不会向未登录的用户显示

javascript - 如何将套接字传递给 Node 中的集群

javascript - 如果元素有类,则切换元素

JavaScript 全局化 : How to compare two dates?

javascript - 动态卸载和重新加载 js/css 文件时在 extjs 版本之间切换的问题

javascript - 滚动固定的 div 时防止正文滚动?

javascript - 谷歌地图API,如何为多个自定义标记添加标记阴影

javascript - Google OpenID - 如何在 javascript 中使用 checkid_immediate?

javascript - 在子进程和父进程之间共享 ipc 对象