gpt4 book ai didi

javascript - html/jquery 的 if 语句

转载 作者:行者123 更新时间:2023-11-30 12:12:16 25 4
gpt4 key购买 nike

<div class="collapse navbar-collapse navbar-right">
<ul class="nav navbar-nav">
<li class="active"><a href="index.html">Home</a></li>
<li><a href="about-us.html">About Us</a></li>
<li><a href="portfolio.html">Portfolio</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="contact-us.html">Contact</a></li>
</ul>
</div>

我有上面的代码,它突出显示了主页按钮,因为类已设置为事件。

我想做的是,我想放置某种 if 条件,它检测加载了哪些 html 文件,并将类设置为事件状态。

可能类似于 <li (if loaded.(about-us.html):class="active"><a href="about-us.html">About Us</a></li>但这没有用。

最佳答案

只需将其保存在您通常为所有页面加载的一些 js 文件中,并将 id 添加到您的 ul 中,比如 导航在这里。假设您的 url 格式为 - www.somedomain.com/filename.html

HTML

<ul class="nav navbar-nav" id="nav">

JS

(function() {
var nav = document.getElementById('nav'),
anchor = nav.getElementsByTagName('a'),
current = window.location.pathname.split('/')[1];
for (var i = 0; i < anchor.length; i++) {
if(anchor[i].href == current) {
anchor[i].parentNode.className = "active";
}
}
})();

还有 jquery 如下:

$(function() {
$('#nav a[href^="/' + location.pathname.split("/")[1] + '"]')closest('li').addClass('active');
});

关于javascript - html/jquery 的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33428012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com