这里有JavaScript代码,用于检测URL中的一个#,如果检测到,则向元素中添加一个活动类。然而,在第n个孩子选择器的三个案例中,什么都没有发生,我不知道为什么。
switch (window.location.hash) {
case "#MAIN":
$('#tab li a.nav:first').addClass('act').siblings().addClass('inact');
break;
case "#sg2":
$('#tab li a.nav:nth-child(2)').addClass('act').siblings().addClass('inact');
alert($('#tab li a.nav:nth-child(2)').className);
break;
case "#sg3":
$('#tab li a.nav:nth-child(3)').addClass('act').siblings().addClass('inact');
break;
case "#zycsg":
$('#tab li a.nav:nth-child(4)').addClass('act').siblings().addClass('inact');
break;
default:
$('#tab li a.nav:first').addClass('act').siblings().addClass('inact');
}我该如何解决这个问题?
HTML
<div id="tab">
<ul>
<li class="menuItem2"><a href="#MAIN" class="nav" onclick='window.history.pushState("", "", "/#MAIN");'>Home-1</a></li>
<li class="menuItem2"><a href="#sg2" class="nav" onclick='window.history.pushState("", "", "/#sg2");'>HDCYG?</a></li>
<li class="menuItem2"><a href="#sg3" class="nav" onclick='window.history.pushState("", "", "/#sg3");'>Home-3</a></li>
<li class="menuItem2"><a href="#zycsg" class="nav" onclick='window.history.pushState("", "", "/#zycsg");' style="width:300px;">Zinteen youtube collection</a></li>
</ul>
</div>发布于 2013-09-01 20:35:16
你的选择器错了,应该是
$('#tab a.nav:nth-child(n)')或
$('#tab li:nth-child(n) a.nav')您现在正在寻找#选项卡下每个li的第n个子锚。
发布于 2014-07-08 23:25:53
我知道这已经关闭了,但是用href作为你的选择器不是更容易吗?
//get the hash
//find the anchor tag with the matching href and add the act class
//select all of the anchor tags with the nav class but not the nav and act class
var page = window.location.hash;
$('a.nav[href="'+page+'"]').addClass('act');
$('a.nav:not(.act)').addClass('inact');https://stackoverflow.com/questions/18562366
复制相似问题