我目前正试图通过尝试检测浏览器网址来将活动类放入导航...我的代码看起来像

    $('[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>


通过这个例子,Home和Blog li获得了一个活跃的课堂..如果有人可以提示我如何纠正这个短代码,我会很高兴的:)

最好的祝福

最佳答案

尝试比较pathname属性

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>

10-02 13:45