如何确保元素在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');
});
但这似乎并没有任何工作,除非导航后刷新页面。
答
请尝试以下
<script>$("#nav").load("nav.html",function(){
$('#lindex').addClass('active');// add the class after the nav is loaded
});</script>
答
$("#lindex").addClass("Your Class Name");
答
$(document).ready(function() {
console.log("ready!");
$("#nav").load("nav.html");
console.log("after load nav.html!");
//add the class here
$('#lindex').addClass('active');
});
你知道的谐音是什么? – madalinivascu
@madalinivascu我已经在'Ruby on Rails'中使用过它们,但从来没有在纯css/html/js页面中使用过 - 这可能吗? – Bassie
检查此http://*.com/questions/4995440/add-class-to-object-on-page-load – vignesh