簡體   English   中英

如何獲取上一個/下一個未禁用選項的索引(相對於所選選項)?

[英]How to get the index of the previous/next non-disabled option (relative to the selected option)?

請看一下這個:

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

演示: 小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM