按当前浏览器网址

时间:2017-12-10 04:38:50

标签: javascript jquery html

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

    $('[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得到了一个活跃的类..如果有人能给我一个提示如何纠正这个短代码我会很高兴:)

最好的问候

2 个答案:

答案 0 :(得分:1)

尝试比较pathname属性

return location.pathname === this.pathname;

链接路径名示例:

&#13;
&#13;
$('a').each(function(){
   console.log('Link pathname: ', this.pathname);
});
&#13;
a{display:inline-block; padding:5px 10px; background:yellow}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我已经找到了一个有效的解决方案..好吧它不是最好的,但我是新手;)

    $('[ui-nav] a, [data-ui-nav] a').filter( function() {
        if ($(this).attr('href') === '/') {
            if (location.pathname === $(this).attr('href')) {
                return true
            } else { return false }
        } else {
            return location.href.indexOf( $(this).attr('href') ) != -1;
        }
    }).parent().addClass( 'active' );