如何使用jQuery获取选择选项的标签?

128
<select>
<option value="test">label </option>
</select>

可以通过 $select.val() 获取该值。

那么 label 呢?

有没有在 IE6 中也能使用的解决方案?


你的意思是如何获取所选内容的值,也就是所选标签的值? - ant
这个问题应该重新表述为“如何使用jQuery获取选择选项的文本?”,并且所有对标签的引用都应替换为文本,以避免与标签属性混淆。 - Joel Davis
11个回答

251

试试这个:

$('select option:selected').text();

3
这并不总是正确的。选项的描述可以通过“label”属性来指定(除了<= IE7)。请参阅http://www.w3schools.com/tags/att_option_label.asp#gsc.tab=0和http://www.w3.org/TR/html401/interact/forms.html#h-17.6。 - Scott Stafford
3
要获取_label_属性,可以使用以下代码:jQuery('#theid option:selected').attr('label') - David Balažic

23

首先给选择器添加一个id:

<select id=theid>
<option value="test">label </option>
</select>

然后你可以像这样调用所选的标签:

jQuery('#theid option:selected').text()

18

供参考,选项标签还有一个次要的label属性:

//returns "GET THIS" when option is selected
$('#selecter :selected').attr('label'); 

Html

<select id="selecter">
<option value="test" label="GET THIS">
Option (also called label)</option>
</select>

9
我觉得这很有帮助。
$('select[name=users] option:selected').text()

使用this关键字访问选择器。

$(this).find('option:selected').text()

7
要获取下拉菜单中特定选项的标签,您可以尝试使用以下代码--
$('.class_of_dropdown > option[value='value_to_be_searched']').html();

或者

$('#id_of_dropdown > option[value='value_to_be_Searched']').html();

3

试试这个:

$('select option:selected').prop('label');

这将提取出两种<option>元素的显示文本:
  • <option label="foo"><option> -> "foo"
  • <option>bar<option> -> "bar"
如果同时拥有label属性和元素内部文本,则会使用label属性,这与浏览器的行为相同。 出于纪念,此内容在jQuery 3.1.1下进行了测试。

2
$("select#selectbox option:eq(0)").text()

在“option:eq(0)”中的0索引可以替换为您想要检索的任何索引选项。

1

在现代浏览器中,您不需要使用 JQuery 来实现此功能。相反,请使用

document.querySelectorAll('option:checked')

或者指定任何DOM元素而不是document


大概,您想要对元素运行它,而不是整个文档。为了获取文本值,您需要访问 element.textContent - Flimm

0
<SELECT id="sel" onmouseover="alert(this.options[1].text);"
<option value=1>my love</option>
<option value=2>for u</option>
</SELECT>

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接