我目前正在尝试将navigation-menu
where anactive-class
应用于其href
属性与当前 URL 匹配的锚点,因此我可以以一种使其从菜单的其余部分中脱颖而出的方式设置该锚点的样式。
这是我的标记:
<div id="sidebar">
<h2>Navigation menu</h2>
<h2 class="subnav"><a href="menu1/menu_item1">Menu item 1</a></h2>
<h2 class="subnav"><a href="menu1/menu_item2">Menu item 2</a></h2>
<h2 class="subnav"><a href="menu1/menu_item3">Menu item 3</a></h2>
<h2 class="subnav"><a href="menu1/menu_item4">Menu item 4</a></h2>
<h2 class="subnav"><a href="menu1/menu_item5">Menu item 5</a></h2>
</div>
这是 jQuery:
jQuery(function($) {
// get the current url
var path = location.pathname.substring(1);
// defining the top subnav anchor
var $top_item = $('#sidebar h2:nth-child(2) a');
// defining all subnav anchors
var $all_items = $('#sidebar h2.subnav a');
// defining the anchors with a href that matches the current url
var $selected_item = $('#sidebar h2 a[@href$="' + path + '"]');
// setting the selected menu item'class as active
$selected_item.addClass('active');
// THIS IS WHERE I THINK THE ERROR IS
// if none of the h2.subnav's has a url that matches
// the current location then assume that it's the top one that's active:
if ($all_items("href") !== path) $top_item.addClass('active');
});
我正在使用 jQuery 应用活动类,只要锚点 href 和位置 url 之间存在匹配,它就可以正常工作。如果 url 与任何锚点不匹配,我希望将活动类应用于$top_item
. 我的 jQuery 的那部分不起作用。
我看不出错误是什么,但我又有点像 Javascript/jQuery n00b。任何帮助,将不胜感激。