如何同时获得多个选项
假设我有一个下拉菜单:
<select id="color">
<option value="white" selected="selected">White</option>
<option value="black">Black</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="green">Transparent</option>
</select>
我知道在 jQuery 中我可以得到一个带有选项索引的选项,如下所示:
$('#color option:eq(2)') //get 'red'
但是有没有办法一次获取多个选项?我尝试了以下代码:
$('#color option:eq(2, 3)') //Try to get 'Red' and 'Green'
但是
$('#color option:eq([2, 3])') //Try to get 'Red' and 'Green'
都没有工作,如何解决同时获得多个选项的问题?
Suppose I have a drop down menu:
<select id="color">
<option value="white" selected="selected">White</option>
<option value="black">Black</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="green">Transparent</option>
</select>
I know in jQuery I can get a option with option index like this:
$('#color option:eq(2)') //get 'red'
But is there any way to get multiple options at a time ? I tried the following code:
$('#color option:eq(2, 3)') //Try to get 'Red' and 'Green'
and
$('#color option:eq([2, 3])') //Try to get 'Red' and 'Green'
But neither one working, how to workaround to get multiple options at a time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想获取子集,可以使用
.slice()
集合。如果您想获取不同的元素,可以执行以下操作:
jsfiddle 上的代码示例。< /强>
You can use
.slice()
if you want to get a subset of the collection.If you want to get different elements you could do the following:
Code example on jsfiddle.
根据您的其他问题,您可能需要考虑添加一个类到具体选项。这不仅允许您获取多个,还提供了一些上下文:
然后,当您编写逻辑时,您可以执行类似的操作
Based on your other question, you might want to consider adding a class to specific options. This not only allows you to grab multiple ones, but gives some context as well:
Then, when you write your logic, you could do something like
选择元素后,您可以像对待任何其他数组一样对待它:
You can treat it like any other array once you've selected the element: