1

请看看这个:

<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 规范中被省略,没有区别)。
我认为您可以看到问题所在:我正在尝试获取这些索引,但找不到方法。

4

1 回答 1

1

尝试

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

演示:小提琴

于 2013-10-02T04:35:36.590 回答