【问题标题】:jQuery nth-child selector not workingjQuery nth-child 选择器不起作用
【发布时间】:2016-06-30 01:42:55
【问题描述】:

我有一个 div id(拍卖),我想用拍卖列表的子项交换 HTML。但是,jQuery 不能选择拍卖列表 div 的子元素。

这是 HTML:

<div id="all">      
    <div id="auctions"></div>
</div>

<div id="auction-list" class="hide">
    <div class="auction">Test</div>
    <div class="auction">Test</div>
</div>

这是 jQuery:

alert($("#auction-list").children().length);
alert($("#auction-list").html());
alert($("#auction-list:nth-child(1)").html());
alert($("#auction-list:nth-child(2)").html());
$("#auctions").html($("#auction-list:nth-child(1)").html());

这里是 Javascript 警报的输出:

第一个警报

2

第二次警报

<div class="auction">Test</div>
<div class="auction">Test</div>

第三次警报

null

我在这里俯瞰什么?

【问题讨论】:

    标签: jquery css-selectors


    【解决方案1】:

    选择器之间需要一个空格,如下所示:

    alert($("#auction-list :nth-child(1)").html());
    //                    ^-- Space here
    

    使用您的选择器,它正在寻找元素 #auction-list,它是另一个元素的第一个子元素,而您实际上正在寻找的元素是列表的第 n 个子元素。

    【讨论】:

    • 就是这样。我需要在冒号前留一个空格。
    【解决方案2】:

    我认为您不应该在元素 ID 上使用 :nth-child 选择器。它应该是一个分类项目

    喜欢;

    alert($("div.auction-item:nth-child(1)").html());
    

    【讨论】:

      【解决方案3】:

      尝试以下方法:

      $("#auction-list > .auction:nth-child(2)")
      

      看看docs。您正在尝试选择第 n 个 #auction-list 元素而不是其子元素。

      【讨论】:

        【解决方案4】:
        alert($("#auction-list").children().length);
        alert($("#auction-list").html());
        alert($("#auction-list div:nth-child(1)").html());
        alert($("#auction-list div:nth-child(2)").html());
        $("#auctions").html($("#auction-list:nth-child(1)").html());
        

        【讨论】:

          【解决方案5】:

          我遇到了一个问题,点击事件在 IE 和 chrome 中可以正常触发,但在 firefox 中却不能。我忽略了一个错字。以为我会分享以防它对某人有所帮助。

           $(document).ready(function () {
              $(".test table tr:nth-child(1n+2").click(function () {
                      alert(this.id); 
                  });
          });
          

          +2 后我错过了 )。

          JSFiddle:https://jsfiddle.net/xv3bca60/7/

          【讨论】:

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