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

 text1 text2 text3 ...  

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

PS索引:value =“123”=> 0,value =“44”=> 1,…

感谢名单

这样做:

  $("#sel").attr("selectedIndex") 

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

 $("#sel")[0].selectedIndex 

作品: 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); }); 

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

.selectedOption()返回的是实际的选项标记,因此您可以访问.index.value.text – 比典型用法中的索引更方便一些。

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

 $(this).prop('selectedIndex') 

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

 $("#sel").attr("selectedIndex") 

要么

 $("#sel")[0] //to get the DOM element $("#sel")[0].selectedIndex 

你可以在没有jQuery的情况下实现它: var sel = document.getElementById( 'sel' ); var index = sel.selectedIndex; var sel = document.getElementById( 'sel' ); var index = sel.selectedIndex;

在这种情况下,您可以通过检查所选元素之前有多少个兄弟元素来获取元素的索引:

 $('#sel option:selected').prevAll().length; 

使用jquery的标准索引函数,就像在这个代码示例中一样

$("#sel option:selected").index()

标题与问题不完全一致……

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

 option.index // javascript $(option).prop('index') // jquery 

所选 select->选项标签的索引:

 document.getElementById('sel').selectedIndex // javascript