使用jQuery获取所选选项的索引 [英] Get index of selected option with jQuery

查看:87
本文介绍了使用jQuery获取所选选项的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何从HTML < select> 项目获取所选选项的索引有点困惑。



On 这个页面有两种描述的方法。但是,两者总是返回 -1 。这是我的jQuery代码:

  $(document).ready(function(){
$(#dropDownMenuKategorie ).change(function(){
alert($(#dropDownMenuKategorie option:selected)。index());
alert($(select [name ='dropDownMenuKategorie'] option:选择)。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>购物< / option>
< option value =bildung> Bildung< / option>
< / select>
(...)

为什么会这样?在赋值 change()方法的时刻, select 是否有可能不是ready?此外,将 .index()更改为 .val()会返回正确的值,所以这甚至会让我感到困惑第一种方法似乎可以在我测试的浏览器中工作,但选项标签并不真正对应于所有浏览器中的实际元素,所以结果可能会有所不同。



只需使用DOM元素的 selectedIndex 属性:

  alert($(#dropDownMenuKategorie)[0] .selectedIndex); 



更新:



prop 方法可用于读取属性:

  alert ($( #dropDownMenuKategorie)丙( '的selectedIndex')); 


I'm a little bit confused about how to get an index of a selected option from a HTML <select> item.

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());
    });
});

and in 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>
(...)

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.

Just use the selectedIndex property of the DOM element:

alert($("#dropDownMenuKategorie")[0].selectedIndex);

Update:

Since version 1.6 jQuery has the prop method that can be used to read properties:

alert($("#dropDownMenuKategorie").prop('selectedIndex'));

这篇关于使用jQuery获取所选选项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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