简体   繁体   English

无法将 class 添加到包含的 HTML 文件中的元素

[英]Unable to add class to element in included HTML file

I've used jquery script to load external header file in every html page.我已经使用 jquery 脚本在每个 html 页面中加载外部 header 文件。 But I'm unable to add class so that I can change color of selected navbar list element using jquery.但我无法添加 class 以便我可以使用 jquery 更改所选导航栏列表元素的颜色。 jquery code to include html file in head section: jquery 代码在头部包含 html 文件:

<script>
    $(function() {
        $('.header').load('header.html');
        $('.footter').load('footer.html');
    });
</script>

Here is the code from header.html:这是来自 header.html 的代码:

<ul id="nav-links" class="nav-links">
    <li class="active"><a href="index.html">Home</a></li>
    <li id="nav-prod"><a href="products.html">Products</a></li>
    <li><a href="services.html">Services</a></li>
    <li><a href="contact.html"> Contact Us</a></li>
    <li><a href="cart.html"> Cart</a>
        <span class="cartcount">(0)</span>
    </li>
</ul>

I tried to remove "active" class from Home page and add it to products page when it's clicked using ready() in jquery.我尝试从主页中删除“活动”class,并在使用 jquery 中的 ready() 单击它时将其添加到产品页面。

if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
   ready()
}


function ready() {
$(".active").removeClass("active");
$("#nav-prod").addClass("active");
}

But it's not working.但它不起作用。

Since load() is an async operation, there is no guarantee that ready() runs before header.html is added to the page.由于 load() 是异步操作,因此无法保证 ready() 在 header.html 添加到页面之前运行。 Try using the load callback here instead.请尝试在此处使用加载回调。

$(function() {
  $('.header').load('header.html', function() {
    $(".active").removeClass("active");
    $("#nav-prod").addClass("active");
  });
  $('.footter').load('footer.html');
});

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

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