我对如何从 HTML <select>
项目中获取所选选项的索引有点困惑。
此 页面上描述了两种方法。但是,两者总是返回 -1
。这是我的 jQuery 代码:
$(document).ready(function(){
$("#dropDownMenuKategorie").change(function(){
alert($("#dropDownMenuKategorie option:selected").index());
alert($("select[name='dropDownMenuKategorie'] option:selected").index());
});
});
在 html 中
(...)
<select id="dropDownMenuKategorie">
<option value="gastronomie">Gastronomie</option>
<option value="finanzen">Finanzen</option>
<option value="lebensmittel">Lebensmittel</option>
<option value="gewerbe">Gewerbe</option>
<option value="shopping">Shopping</option>
<option value="bildung">Bildung</option>
</select>
(...)
为什么会有这种行为? select
在分配其 change()
方法时是否有可能未“准备好”?此外,将 .index()
更改为 .val()
返回正确的值,这让我更加困惑。
原文由 Valentino Ru 发布,翻译遵循 CC BY-SA 4.0 许可协议
第一种方法似乎适用于我测试的浏览器,但选项标签并不真正对应于所有浏览器中的实际元素,因此结果可能会有所不同。
只需使用 DOM 元素的
selectedIndex
属性:更新:
由于版本 1.6 jQuery 具有
prop
可用于读取属性的方法: