请看一下这个:
<select>
<optgroup label="Group 1">
<option>1.1
<option>Get my index (1)!
<option disabled>1.3
<optgroup label="Group 2">
<option selected>I am selected
<option disabled>2.2
<optgroup label="Group 3">
<option disabled>3.1
<option>Get my index (6)!
<option>3.3
</select>
<script>
var sIndex = $("select").prop("selectedIndex");
var nextClosestIndex = $("select").find("option").filter(function (i) {
return $(this).prop("disabled") === false && this.index > sIndex
}).prop("index");
alert(nextClosestIndex + ', which is right by accident, but I strongly dislike this way');
var prevClosestIndex = "I have no idea how to get 1";
alert(prevClosestIndex);
</script>
(在 HTML5 规范中省略了结束标记,这没有区别)。
我想你可以看到问题所在:我正在尝试获取这些索引,但找不到方法。
最佳答案
尝试
var sIndex = $("select").prop("selectedIndex");
var $opts = $("select").find("option");
var $next = $opts.slice(sIndex + 1).not(':disabled').first();
var nextClosestIndex = $opts.index($next)
var $prev = $opts.slice(0, sIndex).not(':disabled').last();
var prevClosestIndex = $opts.index($prev)
console.log(nextClosestIndex);
console.log(prevClosestIndex);
演示:Fiddle
关于javascript - 如何获取上一个/下一个非禁用选项的索引(相对于所选选项)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19129976/