Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery第n个子选择器不使用jQuery_Javascript_Jquery_Css_Jquery Selectors - Fatal编程技术网

Javascript jQuery第n个子选择器不使用jQuery

Javascript jQuery第n个子选择器不使用jQuery,javascript,jquery,css,jquery-selectors,Javascript,Jquery,Css,Jquery Selectors,我这里有JavaScript代码来检测中的#,然后在检测到的情况下向元素添加活动类。然而,在使用第n个子选择器的三个案例中,什么都没有发生,我不知道为什么 switch (window.location.hash) { case "#MAIN": $('#tab li a.nav:first').addClass('act').siblings().addClass('inact'); break; case "#sg

我这里有JavaScript代码来检测中的
#
,然后在检测到的情况下向元素添加活动类。然而,在使用第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


您的选择器错误,应该是

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


您现在正在查找#tab

下每个li的第n个子锚点,我知道这已经关闭了,但是使用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');

我们必须看到html,因为jQuery代码本身没有什么问题,只是有点多余。此外,您的警报将始终返回未定义,因为jQuery选择器始终返回jQuery对象,而不是DOM元素,因此为了访问className属性,您应该使用
alert($('#tab li a.nav:nth child(2)')[0].className)
@Neils我添加了HTML1只是一个想法-问题可能是在执行
#MAIN
块后,所有链接都有
Incat
类,这就隐藏了以后应用
act
类的影响吗?@SteveWilkes当点击链接时,它会得到
act
类,而所有其他类都会进入
incat
$('#tab li a.nav')。removeClass('act')。addClass('incat')$(本条)。addClass(“法案”);
$('#tab li:nth-child(n) a.nav')
//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');