2014-10-08 90 views
0

我正在使用无序列表构建一个非常简单的菜单。我希望当前页面在被选中时突出显示。“活动”类不添加到所有列表项目

我的问题是,其中一个菜单项获得点击时添加的active类,但其他都不是当我从菜单中更改页面时,这就是为什么这对我来说很困惑。当我检查时,控制台中没有错误。我甚至尝试过从this SO post正则表达式的方法,但它仍然不适合我的所有菜单项。

HTML

<div class="page-menu"> 
    <ul> 
    <li class="list-item"><a href="#Item1">Item 1</a></li> 
    <li class="list-item"><a href="#Item2">Item 2</a></li> 
    <li class="list-item"><a href="#Item3">Item 3</a></li> 
    </ul> 
</div> 

CSS

.active { 
    background-color:red; 
} 

jQuery的

$(document).ready(function(){ 
    $('.page-menu a').each(function(index) { 
     if(this.href.trim() == window.location) 
      $(this).addClass("active"); 
    }); 
}); 

为什么active将被添加到一个列表项的任何想法,但不是别人?

+3

因为'href'为他们的一个只匹配?而你的加入类'selected',而不是'active' – tymeJV 2014-10-08 14:32:50

+0

@tymeJV底部的类是一个错字...现在更新了。我认为'if'正在检查当前的URL ......是不是正确的? – Brian 2014-10-08 14:35:44

+0

这是,但为什么你会期望添加超过1个活动类? – tymeJV 2014-10-08 14:37:05

回答

0

我认为你的问题可能存在一些混淆。根据您的问题和意见,您需要选择当前位置。因此,在任何给定时间应该只有一个位置选择,因为浏览器窗口在时间只能导航到一个位置。

此外,你验证href属性包含针对window.location.href它返回一个完整的URL(即http://www.example.com/something.html#Item1)哈希(#Item1)。在这种情况下,你的价值将永远不会匹配。

而是试图通过对像window.location.hash所以返回的值匹配:

$(function() { 
    $('.page-menu a[href="' + window.location.hash + '"]').addClass("active"); 
}); 

您可以通过使用jQuery attribute selectors确定一个位置完全消除环路。

// Test snippet to add hash to current URL. 
 
window.location.hash = "Item1"; 
 

 
$(function() { 
 
    $('.page-menu a[href="' + window.location.hash + '"]').addClass("active"); 
 
});
.active { 
 
    background-color:red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class="page-menu"> 
 
    <ul> 
 
    <li class="list-item"><a href="#Item1">Item 1</a></li> 
 
    <li class="list-item"><a href="#Item2">Item 2</a></li> 
 
    <li class="list-item"><a href="#Item3">Item 3</a></li> 
 
    </ul> 
 
</div>

JSFiddle