使用 jQuery 获取所选选项的索引 [英] Get index of selected option with jQuery
问题描述
我对如何从 HTML 项目中获取所选选项的索引有点困惑.
I'm a little bit confused about how to get an index of a selected option from a HTML <select>
item.
在 这个页面有两种方法描述.但是,两者总是返回 -1
.这是我的 jQuery 代码:
On this page there are two methods described. However, both are always returning -1
. Here is my jQuery code:
$(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>
(...)
为什么会有这种行为?在分配 change()
方法时,select
是否有可能没有准备好"?此外,将 .index()
更改为 .val()
会返回正确的值,所以这让我更加困惑.
Why this behavior? Is there any chance that the select
is not "ready" at the moment of assigning its change()
method? Additionally, changing .index()
to .val()
is returning the right value, so that's what confuses me even more.
推荐答案
第一种方法在我测试的浏览器中似乎有效,但选项标签并不真正对应所有浏览器中的实际元素,因此结果可能因人而异.
The first methods seem to work in the browsers that I tested, but the option tags doesn't really correspond to actual elements in all browsers, so the result may vary.
只需使用 DOM 元素的 selectedIndex
属性:
Just use the selectedIndex
property of the DOM element:
alert($("#dropDownMenuKategorie")[0].selectedIndex);
更新:
从 1.6 版开始,jQuery 具有可用于读取属性的 prop
方法:
alert($("#dropDownMenuKategorie").prop('selectedIndex'));
这篇关于使用 jQuery 获取所选选项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!