如何获取上一个/下一个非禁用选项的索引(相对于所选选项)?

时间:2013-10-02 04:23:11

标签: javascript jquery html5

请看一下:

<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规范中省略了结束标记,没有区别) 我认为你可以看到问题:我正试图获得这些指数,但找不到方法。

1 个答案:

答案 0 :(得分: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);

演示:Fiddle