【问题标题】:jQuery nth-child selector not working with jQueryjQuery nth-child 选择器不适用于 jQuery
【发布时间】:2013-09-01 20:03:26
【问题描述】:

我在这里有 JavaScript 代码来检测URL 中的#,然后在检测到时将活动类添加到元素。但是,在使用 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>

【问题讨论】:

  • 我们必须查看 html,因为您的 jQuery 代码本质上没有任何问题,只是有点多余。此外,您的警报将始终返回 undefined,因为 jQuery 选择器始终返回 jQuery 对象,而不是 DOM 元素,因此为了访问 className 属性,您应该使用 alert($('#tab li a.nav:nth-child(2)')[0].className);
  • @Neils 我已经添加了 html
  • 只是一个想法 - 问题可能是在 #MAIN 块执行后所有链接都有 inact 类,并且隐藏了稍后应用 act 类的影响?
  • @SteveWilkes 当链接被点击时,它会得到act 类,而所有其他的都是inact
  • $('#tab li a.nav').removeClass('act').addClass('inact'); $(this).addClass('act');

标签: javascript jquery css jquery-selectors


【解决方案1】:

你的选择器错了,应该是

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

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

你现在正在寻找 #tab 下每个 li 的第 n 个子锚

【讨论】:

    【解决方案2】:

    我知道这已经关闭了,但是使用 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');
    

    【讨论】:

      猜你喜欢
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-31
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多