如何获取select-> option标签的索引

Vov*_*4ik 18 indexing jquery

<select id="sel">
<option value="123" selected="selected">text1</option>
<option value="44">text2</option>
<option value="882">text3</option>
...
</select>
Run Code Online (Sandbox Code Playgroud)

如何使用jQuery获取所选选项的索引?可能是.index(subject),但所有测试的可能性都没有用......

PS索引:value ="123"=> 0,value ="44"=> 1,...

感谢名单

Chr*_*ini 17

只有鲍勃的第二个答案是正确的:

$("#sel")[0].selectedIndex
Run Code Online (Sandbox Code Playgroud)

作品:http: //jsfiddle.net/b9chris/wxeVN/1/

.attr()仅当用户(或浏览器的DOM还原)未更改自页面加载后选择的选项时才使用有效:http: //jsfiddle.net/b9chris/wxeVN/

您可以将其实现为jQuery扩展,并在此过程中获取更多信息:

(function($) {
    $.fn.selectedOption = function() {
        var sel = this[0];
        return sel.options[sel.selectedIndex];
    };
})(jQuery)

$('button').click(function() {
    $('#output').text('selected index: ' + $('select').selectedOption().index);
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/b9chris/wxeVN/102/

什么是通过返回.selectedOption()的是实际的选项标签,这样你就可以访问.index,.value以及.text-有点不仅仅是在典型使用该指数更方便.


Jus*_*gan 10

在我写这篇文章时,尽管近五年前被指出,但其中两个最佳答案(包括已接受的答案)是不正确的.attr("selectedIndex")什么也不做,因为它selectedIndex是实际DOM元素的属性,而不是HTML属性.你需要使用prop:

$(this).prop('selectedIndex')
Run Code Online (Sandbox Code Playgroud)

交互式演示将此与不正确的版本进行比较:http://jsfiddle.net/uvwkD/


Bob*_*Bob 5

$("#sel").attr("selectedIndex")
Run Code Online (Sandbox Code Playgroud)

要么

$("#sel")[0] //to get the DOM element
$("#sel")[0].selectedIndex
Run Code Online (Sandbox Code Playgroud)


小智 3

这将做到这一点:

   $("#sel").attr("selectedIndex")
Run Code Online (Sandbox Code Playgroud)

  • 请注意,我的答案是在 2009 年写的 - 当时它**是**正确的。从那时起,jQuery 发生了变化。 (7认同)
  • 这是错误的。`attr("selectedIndex")` 什么都不做,你需要 `prop("selectedIndex")`。演示:http://jsfiddle.net/Nj85e/ (3认同)
  • 这混淆了 attr 和 prop 之间的区别。请注意,一旦您更改本示例中下拉列表中的选定项目,selectedIndex 不会更改,并且不正确:http://jsfiddle.net/b9chris/wxeVN/ (2认同)