Javascript jQuery第n个子选择器不使用jQuery
我这里有JavaScript代码来检测中的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
#
,然后在检测到的情况下向元素添加活动类。然而,在使用第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');