我目前正在尝试创建一个导航菜单,其中活动类应用于具有与当前URL匹配的href的锚点,因此我可以使该锚点的样式使其从菜单的其余部分中脱颖而出.
这是我的加价:
这是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应用active-class,只要锚点href和位置url之间存在匹配,它就可以正常工作.如果url与任何锚点都不匹配,我希望将active-class应用于$ top_item.我的jQuery的那部分不起作用.
我看不出错误是什么,但是我又有点像Javascipt/jQuery n00b.任何帮助,将不胜感激.
这应该是您想要的:标记匹配的链接,如果失败,请标记您的默认链接.
function markActiveLink() { //Look through all the links in the sidebar $("div#sidebar a").filter(function() { //Take the current URL and split it into chunks at each slash var currentURL = window.location.toString().split("/"); //return true if the bit after the last slash is the current page name return $(this).attr("href") == currentURL[currentURL.length-1]; //when the filter function is done, you're left with the links that match. }).addClass("active"); //Afterwards, look back through the links. If none of them were marked, //mark your default one. if($("div#sidebar a").hasClass("active") == false) { $("div#sidebar h2:nth-child(2) a").addClass("active"); } } markActiveLink();
另外,我在jQuery Docs站点上找到了关于此的官方教程- 滚动到底部以查看jQuery代码.它比我的更紧,虽然它不适合你的情况.