gpt4 book ai didi

javascript - 按当前浏览器 url 过滤 li 元素

转载 作者:行者123 更新时间:2023-12-03 02:53:29 24 4
gpt4 key购买 nike

我目前正在尝试通过尝试检测浏览器 URL 将事件类放入导航中...我的代码如下所示

    $('[ui-nav] a, [data-ui-nav] a').filter( function() {
console.log(location.href)
console.log($(this).attr('href'))
return location.href.indexOf( $(this).attr('href') ) != -1;
}).parent().addClass( 'active' );

输出:

app.js:12758 http://localhost:8000/blog/welcome-to-my-blog
app.js:12759 /
app.js:12758 http://localhost:8000/blog/welcome-to-my-blog
app.js:12759 /blog
app.js:12758 http://localhost:8000/blog/welcome-to-my-blog
app.js:12759 /profile
app.js:12758 http://localhost:8000/blog/welcome-to-my-blog
app.js:12759 /test

我的导航:

Home -> /
Blog -> /blog
Profile -> /profile
Testing -> /test



<ul class="nav" data-ui-nav>
<li class="nav-header hidden-folded">
<span class="text-xs text-muted">Main</span>
</li>
<li>
<a href="/">
<span class="nav-icon">
<i class="material-icons">
play_circle_outline
</i>
</span>
<span class="nav-text">Home</span>
</a>
</li>
<li>
<a href="/blog">
<span class="nav-icon">
<i class="material-icons">
play_circle_outline
</i>
</span>
<span class="nav-text">Blog</span>
</a>
</li>
<li>
<a href="/profile">
<span class="nav-icon">
<i class="material-icons">
play_circle_outline
</i>
</span>
<span class="nav-text">Profile</span>
</a>
</li>
<li>
<a href="/test">
<span class="nav-icon">
<i class="material-icons">
play_circle_outline
</i>
</span>
<span class="nav-text">Testing</span>
</a>
</li>
</ul>

通过这个例子,主页和博客得到了一个活跃的类..如果有人能给我提示如何纠正这个短代码,我会很高兴:)

最诚挚的问候

最佳答案

尝试比较路径名属性

return location.pathname === this.pathname;

链接路径名示例:

$('a').each(function(){
console.log('Link pathname: ', this.pathname);
});
a{display:inline-block; padding:5px 10px; background:yellow}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://stackoverflow.com/test">https://stackoverflow.com/test</a>
<a href="/profile">/profile</a>
<a href="/">/</a>

关于javascript - 按当前浏览器 url 过滤 li 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47735924/

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