如何确保元素在PageLoad上添加类之前已加载

问题描述:

我有以下代码,它首先在页面加载时将导航栏加载到网站(这是为了不必为每个导航条创建新的导航栏页):如何确保元素在PageLoad上添加类之前已加载

<div id="nav"></div>

<script>$("#nav").load("nav.html");</script>

,并显示出该页面的 “活动” 选项卡,我有以下脚本:

<script> 
    window.onload = function() { 
     document.getElementById('lindex').className = 'active'; 
    }; 
</script> 

然而,在页面加载时,我在控制台中看到此错误(为document.getElementById线):

index.html:70 Uncaught TypeError: Cannot set property 'className' of null

当我浏览到该页面的“活动”选项卡中不会更新。奇怪的是,它似乎在我重新加载页面时添加了类,但是间歇性地添加了该类。有谁知道为什么会发生这种情况?

下面是导航栏(nav.html)代码:

<nav class="navbar navbar-inverse "> 
    <div class="container"> 
    <div class="navbar-header"> 
     <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> 
     <span class="sr-only">Toggle navigation</span> 
     <span class="icon-bar"></span> 
     <span class="icon-bar"></span> 
     <span class="icon-bar"></span> 
     </button> 

    <a href="#" class="navbar-left navbar-logo"><img src="/img/logo.png"></a> 

    </div> 
    <div id="navbar" class="navbar-collapse collapse"> 
     <ul class="nav navbar-nav"> 
     <li id="lindex" class="listitem"><a href="index.html">Home</a></li> 
     <li id="lpandp" class="listitem"><a href="productsandpurchasing.html">Products & Purchasing</a></li> 
     <li><a href="#about">Freight & Distribution</a></li> 
     <li><a href="#about">Blog</a></li> 
     <li><a href="#contact">Contact Us</a></li> 
     <li class="dropdown"> 
     </li> 
     </ul> 
    </div> 
    </div> 
</nav> 

我也曾尝试:

$(function() { 
    $('#about').addClass('expand'); 
}); 

但这似乎并没有任何工作,除非导航后刷新页面。

+0

你知道的谐音是什么? – madalinivascu

+0

@madalinivascu我已经在'Ruby on Rails'中使用过它们,但从来没有在纯css/html/js页面中使用过 - 这可能吗? – Bassie

+0

检查此http://*.com/questions/4995440/add-class-to-object-on-page-load – vignesh

请尝试以下

<script>$("#nav").load("nav.html",function(){ 
    $('#lindex').addClass('active');// add the class after the nav is loaded 
});</script> 

$("#lindex").addClass("Your Class Name"); 
+0

我已经尝试过,类似于我的解决方案中的脚本,它似乎并未等待元素在尝试添加类之前加载。其他答案似乎虽然 – Bassie

+0

虽然此代码片段可以解决问题,[包括解释](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)真的有助于改善您的帖子的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要使用解释性注释来挤占代码,因为这会降低代码和解释的可读性! – FrankerZ

 $(document).ready(function() { 
      console.log("ready!"); 
      $("#nav").load("nav.html"); 
      console.log("after load nav.html!"); 
        //add the class here 
      $('#lindex').addClass('active'); 

     });