【发布时间】:2012-04-10 05:38:17
【问题描述】:
假设我有一个包含 3 个值的下拉列表(选择标签)。我们的第一个选项的值为“”。第二个选项的值为“某物”。第三个选项的值为“其他”。如何获得第二个选项的 innerHTML(文本)?我不想对其进行硬编码,以便每次都采用第二个选项。我想确保它是第一个设置了值的选项。
【问题讨论】:
标签: jquery select drop-down-menu option
假设我有一个包含 3 个值的下拉列表(选择标签)。我们的第一个选项的值为“”。第二个选项的值为“某物”。第三个选项的值为“其他”。如何获得第二个选项的 innerHTML(文本)?我不想对其进行硬编码,以便每次都采用第二个选项。我想确保它是第一个设置了值的选项。
【问题讨论】:
标签: jquery select drop-down-menu option
var result = $('#selectId option[value!=""]').first().html();
或:
var result = $('#selectId option[value!=""]:first').html();
描述:选择不具有指定属性的元素,或者具有指定属性但不具有特定值的元素。
描述:选择第一个匹配的元素。 :first 伪类等价于 :eq(0)。也可以写成:lt(1)
注意,所有<option>s 必须具有value 属性才能使选择器按预期工作。如果不能保证使用这个:
var result = $('#selectId option[value!=""][value]:first').html();
说明:选择具有指定属性的元素,具有任意值。
【讨论】:
$('#selectId option[value!=""]').first().attr('selected', 'selected')
$('#selectId option[selected!=""]').first().html();
如果我说得对,你想从下拉尝试中获得第二个元素
$('select[name=thename] option:eq(1)').text();
【讨论】:
我喜欢简单,所以我会根据结构为您提供两种方法。我通常不按名称选择,因为代码更复杂且不需要 IMO。
如果 HTML 只有一个没有 id 的类:
<select class='example'>
<option value=''>Text 0</option>
<option value='something'>Text 1</option>
<option value='something else'>Text 2</option>
</select>
$('select.example option:eq(1)').text(); // Text 1
如果 HTML 有一个 id,这是获取文本最有效的方法:
<select id='example'>
<option value=''>Text 0</option>
<option value='something'>Text 1</option>
<option value='something else'>Text 2</option>
</select>
$('#example option:eq(1)').text(); // Text 1
【讨论】: