如何在jQuery中选择一系列元素 [英] How to select a range of elements in jQuery

查看:121
本文介绍了如何在jQuery中选择一系列元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<div id="myDiv">
     <a>...</a>
     <a>...</a>
     <a>...</a>
     <a>...</a>
     <a>...</a>
     <a>...</a>
</div>

如果你想选择第二,第三和第四 a 标签,你会怎么做?我唯一能想到的是:

If you wanted to select the 2nd, 3rd and 4th a tags in the above example, how would you do that? The only thing I can think of is:

$("#myDiv a:eq(1), #myDiv a:eq(2), #myDiv a:eq(3)")

但是这看起来并不是非常高效或漂亮。我想你也可以选择所有 a s然后对它们运行 .each ,但这可能会非常如果还有更多 a s,效率低下。

But that doesn't look to be very efficient or pretty. I guess you could also select ALL the as and then do run .each over them, but that could get very inefficient if there were a lot more as.

推荐答案

jQuery < a href =http://docs.jquery.com/Traversing/slice =noreferrer> slice()函数获取第一个和最后一个所需元素的索引选择匹配元素的子集。注意它不包括最后一个元素本身。

jQuery slice() function taking indexes of the first and the last needed elements selects a subset of the matched elements. Note what it doesn't include last element itself.

在您的特定情况下,您应该使用

In your particular case you should use

$("#myDiv a").slice(1, 4)

这篇关于如何在jQuery中选择一系列元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆