简体   繁体   English

当我知道ID存在时,为什么document.getElementById()返回null值?

[英]Why is document.getElementById() returning a null value when I know the ID exists?

I'm working on some custom Javascript for a CMS template at work. 我正在为工作中的CMS模板开发一些自定义Javascript。 I want to be able to make a certain <li> element on the page receive the class of "current" for that page only. 我希望能够在页面上创建某个<li>元素,只接收该页面的“当前”类。 So in the global page head I have something like this: 所以在全局页面头我有这样的事情:

<script type="text/javascript">
    function makeCurrent(id) {
      var current = document.getElementById(id);
      current.setAttribute("class", "current"); // for most browsers
      current.setAttribute("className", "current"); // for ie
    }
</script>

Then in each individual page <head> , I have something like this: 然后在每个单独的页面<head> ,我有这样的事情:

<script type="text/javascript">makeCurrent("undergraduate")</script>

On the page I have a nav <ul> , with something like: 在页面上我有一个nav <ul> ,类似于:

<li id="undergraduate"><a href="...">Undergraduate Program</a></li>
<li id="graduate"><a href="...">Graduate Program</a></li>

etc.

When I load the page, the class is not applied. 当我加载页面时,不应用该类。 When I look in the Firebug console, it gives the error message: 当我查看Firebug控制台时,它会显示错误消息:

current is null
(x)  current.setAttribute("class", "current"); 

I'm still getting the hang of writing solid, raw javascript (learning backwards after jQuery, you know how it goes), but I want to write it in just JS. 我仍然忙于编写可靠的原始javascript(在jQuery之后向后学习,你知道它是怎么回事),但我想用JS编写它。 What idiotic newbie mistake am I making? 我正在做什么愚蠢的新手错误?

Thanks everyone! 感谢大家!

If you execute the javascript before the DOM tree has finished loading, it will return null. 如果在DOM树加载完成之前执行javascript,它将返回null。 So an idea would be to call the function all the way at the end before you close the body tag. 所以一个想法是在关闭body标签之前最后调用函数。

This is why most JavaScript libraries have support for a dom-ready event, modern browsers have this as well (domcontentloaded) however for wide browser support it's a little trickier to do it for yourself (well, not that difficult, 3 or 4 different ways I think.) 这就是为什么大多数JavaScript库都支持dom-ready事件的原因,现代浏览器也支持这种情况(domcontentloaded)但是对于广泛的浏览器支持来说,为自己做这件事有点棘手(好吧,不是那么困难,3或4种不同的方式)我认为。)

The element does not exist yet when that script is being evaluated. 在评估该脚本时,该元素尚不存在 Put it in the body's onload handler or something instead, so it executes once the DOM is in place. 把它放在body的onload处理程序或者其他东西中,所以它在DOM就位后执行。

An example of how to do this without touching any markup: 如何在不触及任何标记的情况下执行此操作的示例:

function callWhenLoaded(func) {
  if (window.addEventListener) {
    window.addEventListener("load", func, false);
  } else if (window.attachEvent) {
    window.attachEvent("onload", func);
  }
}

callWhenLoaded(function() { makeCurrent("undergraduate"); });

The DOM is not fully loaded if you run makeCurrent in your head. 如果在makeCurrent运行makeCurrent ,则DOM未完全加载。 You should put that script after your <li> tags. 之后,你可以把那个剧本<li>标记。

Your code can be optimized: you can set a class attribute directly with current.className = 'current'; 您的代码可以优化:您可以使用current.className = 'current';直接设置class属性current.className = 'current'; .

The reason is that your script is being run before the page load is complete, and therefore before the DOM is populated. 原因是您的脚本在页面加载完成之前运行,因此在填充DOM之前。

You need to make sure you only call the function after page load is complete. 您需要确保在页面加载完成后才调用该函数。 Do this by triggering it using document.onload() or an onload event on the body tag. 通过使用document.onload()或body标签上的onload事件触发它来完成此操作。

After all the technical answers have been spewed out already, I'm going to skip all those which it very well could be and go for some of the more obvious ones I've run into which have caused me to facepalm once I've realised: 在所有的技术答案已经喷出之后,我将跳过所有那些它本来可能成为的东西并去寻找一些我已经遇到的更明显的答案,一旦我意识到这一点就让我面对面:

  • Typo in the identity 错字的身份
  • The identity isn't what you think it is because it's being generated or partially generated by the web framework you're using ie in ASP.NET you could set the client id to "MyControl" only to find that by the time it is rendered in the client it's "Page_1$Control_0$MyControl$1" 身份不是您认为的,因为它是由您正在使用的Web框架生成或部分生成的,即在ASP.NET中,您可以将客户端ID设置为“MyControl”,但只有在它被渲染时才能找到它在客户端它是“Page_1 $ Control_0 $ MyControl $ 1”
  • You've prepended it with a # in one or more of the incorrect places, for instance, although you're not using jQuery in your example if the object id is MyControl, in jQuery and CSS you reference it using #MyControl, but in the actual id of the object, you didn't use #. 例如,你已经在一个或多个不正确的地方用#前缀了它,虽然如果对象id是MyControl你没有在你的例子中使用jQuery,在jQuery和CSS中你使用#MyControl引用它,但是对象的实际id,你没有使用#。 In document.getElementById() you don't use a # like you would in jQuery and CSS, but you may have used it inadvertently. 在的document.getElementById()你喜欢,你会在jQuery和CSS使用#,但你可能无意中使用它。
  • You've set the name element in the control instead of the id. 您已在控件中设置name元素而不是id。

As other people have mentioned though, it could be down to not waiting for the element to be available at the time you're referencing it. 正如其他人提到的那样,可能是因为在你引用元素时没有等待元素可用。

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

相关问题 当存在具有该 ID 的元素时,为什么 document.getElementById() 返回 null? - Why is document.getElementById() returning null when there is an element with that Id? 为什么document.getElementById返回空值? - Why is document.getElementById returning a null value? 当元素是空文本框时,Javascript document.getElementById(&quot;id&quot;).value 返回 null 而不是空字符串 - Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box document.getElementById返回null - document.getElementById is returning null document.getElementById(&#39;ID&#39;)是否仅在我的部分代码中返回null - document.getElementById('ID') is it returning null in only part of my code document.getElementById()不断返回NULL-如何查找值 - document.getElementById() keeps returning NULL - how to find value 搜索div ID时Document.getelementbyId返回null - Document.getelementbyId returns null when searching for div id document.getElementById在单击按钮时返回null - document.getElementById is returning null on the button click CKEditor主体上的Document.getElementById返回null - Document.getElementById on CKEditor body returning null document.getElementById 每次都返回 null 或 undefined - document.getElementById is returning null or undefined everytime
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM