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

发布于 2024-09-25 02:42:02 字数 1085 浏览 7 评论 0原文

我正在工作中为 CMS 模板编写一些自定义 Javascript。我希望能够使页面上的某个

  • 元素仅接收该页面的“当前”类。因此,在全局页面标题中,我有这样的内容:
  • <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>
    

    然后在每个单独的页面 中,我有这样的内容:

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

    在页面上,我有一个导航

      < /code>,类似于:

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

    当我加载页面时,未应用该类。当我查看 Firebug 控制台时,它给出了错误消息:

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

    我仍在掌握编写可靠的原始 javascript 的窍门(在 jQuery 之后向后学习,你知道它是如何进行的),但我想只用 JS 编写它。我犯了什么愚蠢的新手错误?

    谢谢大家!

    I'm working on some custom Javascript for a CMS template at work. I want to be able to make a certain <li> element on the page receive the class of "current" for that page only. 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:

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

    On the page I have a nav <ul>, with something like:

    <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:

    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. What idiotic newbie mistake am I making?

    Thanks everyone!

    如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

    扫码二维码加入Web技术交流群

    发布评论

    需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

    评论(5

    动听の歌 2024-10-02 02:42:02

    如果在 DOM 树完成加载之前执行 JavaScript,它将返回 null。因此,一个想法是在关闭 body 标记之前在最后一直调用该函数。

    这就是为什么大多数 JavaScript 库都支持 dom-ready 事件,现代浏览器也有这个(domcontentloaded),但是对于广泛的浏览器支持,自己做这件事有点棘手(好吧,没那么困难,有 3 或 4 种不同的方式我认为。)

    If you execute the javascript before the DOM tree has finished loading, it will return null. So an idea would be to call the function all the way at the end before you close the body tag.

    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.)

    天赋异禀 2024-10-02 02:42:02

    当评估该脚本时,元素尚不存在。将其放入主体的 onload 处理程序或其他内容中,以便在 DOM 就位后执行。

    如何在不触及任何标记的情况下执行此操作的示例:

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

    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.

    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"); });
    
    水水月牙 2024-10-02 02:42:02

    如果您在脑海中运行 makeCurrent,则 DOM 尚未完全加载。您应该将该脚本放在

  • 标记之后
  • 您的代码可以优化:您可以直接使用 current.className = 'current'; 设置 class 属性。

    The DOM is not fully loaded if you run makeCurrent in your head. You should put that script after your <li> tags.

    Your code can be optimized: you can set a class attribute directly with current.className = 'current';.

    不语却知心 2024-10-02 02:42:02

    原因是您的脚本在页面加载完成之前运行,因此在填充 DOM 之前运行。

    您需要确保仅在页面加载完成后调用该函数。通过使用 document.onload() 或 body 标记上的 onload 事件触发它来执行此操作。

    The reason is that your script is being run before the page load is complete, and therefore before the DOM is populated.

    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.

    雄赳赳气昂昂 2024-10-02 02:42:02

    在所有的技术答案都已经吐出来之后,我将跳过所有那些很可能的答案,而去寻找一些我遇到过的更明显的答案,一旦我意识到这些答案,这些答案就会让我捂脸:

    • 身份中的拼写错误
    • 身份不是您想象的那样,因为它是由您正在使用的 Web 框架生成或部分生成的,即在 ASP.NET 中,您可以将客户端 id 设置为“MyControl”,结果却发现通过 例如,在客户端中呈现它时,它是“Page_1$Control_0$MyControl$1”
    • 您在一个或多个不正确的位置在它前面添加了#,尽管您在示例中没有使用 jQuery,但如果该对象id 是 MyControl,在 jQuery 和 CSS 中,您使用 #MyControl 引用它,但在对象的实际 id 中,您没有使用 #。在 document.getElementById() 中,您不会像在 jQuery 和 CSS 中那样使用 #,但您可能无意中使用了它。
    • 您已在控件中设置 name 元素而不是 id。

    正如其他人所提到的,这可能是因为在引用该元素时没有等待该元素可用。

    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 i.e. 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"
    • 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 #. In document.getElementById() you don't use a # like you would in jQuery and CSS, but you may have used it inadvertently.
    • You've set the name element in the control instead of the 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.

    ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文