如何在jQuery的SELECT元素中选择特定选项? [英] How do you select a particular option in a SELECT element in jQuery?

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

问题描述

如果您知道索引,值或文本.如果您没有直接参考的ID,也可以.

If you know the Index, Value or Text. also if you don't have an ID for a direct reference.

示例标记

<div class="selDiv">
  <select class="opts">
    <option selected value="DEFAULT">Default</option>
    <option value="SEL1">Selection 1</option>
    <option value="SEL2">Selection 2</option>
  </select>
</div>

推荐答案

通过值获取中间选项元素的选择器是

A selector to get the middle option-element by value is

$('.selDiv option[value="SEL1"]')

对于索引:

$('.selDiv option:eq(1)')

对于已知文本:

$('.selDiv option:contains("Selection 1")')

编辑:如上所述,OP可能是在更改下拉菜单的选定项目之后.在1.6版及更高版本中,建议使用prop()方法:

EDIT: As commented above the OP might have been after changing the selected item of the dropdown. In version 1.6 and higher the prop() method is recommended:

$('.selDiv option:eq(1)').prop('selected', true)

在旧版本中:

$('.selDiv option:eq(1)').attr('selected', 'selected')

EDIT2 :在Ryan发表评论之后. 选择10"上的匹配可能是不需要的.我没有找到选择器来匹配全文,但没有找到

EDIT2: after Ryan's comment. A match on "Selection 10" might be unwanted. I found no selector to match the full text, but a filter works:

 $('.selDiv option')
    .filter(function(i, e) { return $(e).text() == "Selection 1"})

EDIT3 :对$(e).text()使用警告,因为它可能包含换行符,导致比较失败.这种情况发生在选项隐含地关闭(无标记):

EDIT3: Use caution with $(e).text() as it can contain a newline making the comparison fail. This happens when the options are implicitly closed (no </option> tag):

<select ...>
<option value="1">Selection 1
<option value="2">Selection 2
   :
</select>

如果仅使用e.text,则会删除任何多余的空格,例如结尾的换行符,从而使比较更加健壮.

If you simply use e.text any extra whitespace like the trailing newline will be removed, making the comparison more robust.

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

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