简体   繁体   English

document.getElementById返回null

[英]document.getElementById is returning null

Here's the relevant HTML: 这是相关的HTML:

<div id="navcontainer">
    <ul id="navlist">
        <li><a href="#tab1">Item one</a></li>
        <li><a href="#tab2">Item two</a></li>
        <li><a href="#tab3">Item three</a></li>
        <li><a href="#tab4">Item four</a></li>
        <li><a href="#tab5">Item five</a></li>
    </ul>
</div>

The content of vertical.js vertical.js的内容

function tabber() {
    var li = document.getElementById("navcontainer");
    var as = document.getElementById('navlist');

    return;
}

window.onload = tabber();

When the tabber() function is executed, the function call to document.getElementById returns null. 执行tabber()函数时,对document.getElementById的函数调用返回null。 Why? 为什么? The element navcontainer definitely exists. 元素navcontainer肯定存在。 Any clues? 有线索吗?

Heh, the devil is in the detail. 嘿,魔鬼在细节。 You are making a mistake while assigning the onload event. 在分配onload事件时你犯了一个错误。

window.onload = tabber();

will assign the result of tabber() to the onload property. tabber()结果分配给onload属性。 Tabber() is executed straight away and not onload . Tabber()是直接执行而不是onload

Change it to 将其更改为

window.onload = function() { tabber(); }

that will work. 那可行。

You're calling the tabber function incorrectly on window load. 你在窗口加载时错误地调用tabber函数。

Change it to 将其更改为

window.onload = tabber;

maybe the fact that you're using the JS keyword 'as' as a variable is the problem. 也许你将JS关键字'as'用作变量这一事实就是问题所在。 remove that first. 首先删除它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM