1

我在这里有 JavaScript 代码来检测URL#中的 a,如果检测到,则将活动类添加到元素中。但是,在使用 nth-child 选择器的三种情况下,什么都没有发生,我不知道为什么。

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>
4

2 回答 2

3

您的选择器错误,应该是

$('#tab a.nav:nth-child(n)')

或者

$('#tab li:nth-child(n) a.nav')

您现在所拥有的是在#tab 下寻找 EACH li 的第 n 个子主播

于 2013-09-01T20:35:16.270 回答
0

我意识到这已经关闭了,但是使用 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');
于 2014-07-08T23:25:53.087 回答