Javascript onload 不工作 ("Uncaught TypeError: Cannot set property ' document.body' of null ")

标签 javascript null onload

这是我的代码:

Javascript:

document.body.onload = function() {
    function UP() {//Ẩn hiện nút UP
        if(window.pageYOffset > window.innerHeight)
            document.getElementById('UP').style.display = "block";
    }
}

HTML 标签:

<button id="UP" onclick="toTop(350);"></button>

CSS 样式:

#UP {display: none;}

我的想法是当我向下滚动时,向上按钮会出现。但不知道为什么,它不会,它甚至返回错误:“Uncaught TypeError: Cannot set property 'document.body' of null”。当然,我确实像这样更改了其他脚本:

function getReady() {
    UP();
}
function UP() {//Ẩn hiện nút UP
    if(window.pageYOffset > window.innerHeight)
        document.getElementById('UP').style.display = "block";
}

HTML 标签:

<body onload="getReady();">
    <button id="UP" onclick="toTop(350);"></button>
</body>

更可怕的是。当我加载站点时,我没有看到 body 标签的 onload attr,浏览器也没有为我返回任何错误。

一些其他信息: 我在两边开发,Cr & FF,都说了同样的问题。 我正在研究 Wordpress 源代码。

最佳答案

只是为了澄清@laruiss 并解释发生了什么,让我们从您的代码开始:

/* body.onload is not recommended, window.onload is. But thats not the main issue*/
window.onload = function() {
    /* You are declaring a function here. Very important: 
     * its a declaration, NOT a function call 
     */
    function UP() {
        if(window.pageYOffset > window.innerHeight)
            document.getElementById('UP').style.display = "block";
    }
    /* So if you want to execute ('call') your function, you have two options:
     * - Remove the declaration around your function aka `function UP(){` and the ending `}`
     * - Call the function here. To make your code work instantly, lets do that.
     */
    UP();
}

当使用 onload 事件时,您实际上是在做正确的事情。确实,不推荐在您的 DOM 中实际执行此操作,但它应该有效。 DOM 加载的最大问题是主观的。一些浏览器会认为内容一出现就加载正文,其他浏览器会等待图像,而旧的 IE 版本不会全部触发!因此,如果您使用推荐的 window.onload,应该没问题,因为它会在 DOM 准备就绪后立即触发 。您可能需要考虑另一个与此相关的重要事件,即 DOMContentLoaded,但它没有得到广泛支持。这里还有更多(也可以通过点击):https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onload

我还想补充一点,即使您将按钮显示出来,它也没有内容,因此它可能显示为空,或者如果您正在重置按钮样式,则根本不会显示。要记住的事情。

关于Javascript onload 不工作 ("Uncaught TypeError: Cannot set property ' document.body' of null "),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26989980/

相关文章:

javascript - 使用 XPage 上的后退按钮后,链接/点击在 Firefox 中不起作用

javascript - 将文本与塞尔维亚西里尔字母相互转换

c++ - 在成员函数中测试 this 指针是否合法 C++?

c - 在 main() 中将指针分配给 NULL 后,for 循环不执行

php - Javascript - 在页面加载期间且仅在页面加载期间发生的 Onclick 事件

javascript - 为什么chrome会在这里抛出 "Uncaught Error: NOT_FOUND_ERR: DOM Exception 8"?

php - 使用 sharer.php 方法的动态 facebook 共享页面

string - Thymeleaf 内联文本将空字符串显示为 'null'

javascript - 尝试与 window.onload 一起执行两个 JavaScript 文件

Java 7 应用程序错误,因为尝试使用新的 Java 8 Javascript 引擎 Nashorn