jQuery限制返回的结果/选择

ttm*_*tmt 3 jquery

是否可以限制jQuery中返回的结果

<body>
  <div id="box">
    <ul>
        <li>One</li>
        <li>Two</li>
        <li>Three</li>
        <li>Four</li>
        <li>Five</li>
        <li>Six</li>        
    </ul>         
  </div>  

  <script>
      $(function(){
          var num = 4;
          console.log( $('#box').children(':first').children(num).text() );
      })
  </script>
</body>
Run Code Online (Sandbox Code Playgroud)

这将输出:

OneTwoThreeFourFiveSix

但我想要:

OneTwoThreeFour

演示小提琴: http: //jsfiddle.net/JLqrc/

Ant*_*ton 6

您可以使用 :lt()

$('#box').children(':first').children(':lt('+num+')');
Run Code Online (Sandbox Code Playgroud)

或者正如MackieeE评论缩短代码

$('#box li:lt('+ num +')').text()
Run Code Online (Sandbox Code Playgroud)

DEMO

文档:http://api.jquery.com/lt-selector/

  • 因此可以简化为:`$('#box li:lt('+ num +')').text()`就我个人而言,我不确定`.children(':first')`部分需要什么 (2认同)