2017-11-02 13 views
2

私はthis questionを見ましたが、他の質問はvalue jQueryを使用していますので、私の質問は異なります。jQueryを使用せずに複数のselectedIndexesを設定するにはどうすればよいですか?


一例で説明する方が簡単です:

const select = document.getElementById('sel'); 
 
const indexes = new Set([0, 2, 4]); 
 

 
Array.prototype.forEach.call(select.options, (opt, i) => { 
 
    opt.selected = indexes.has(i); 
 
});
<select id="sel" multiple size=5> 
 
    <option>one</option> 
 
    <option>two</option> 
 
    <option>three</option> 
 
    <option selected>four</option> 
 
    <option>five</option> 
 
</select>

これは、選択したオプションonethreefiveを設定するための最も効率的な方法ですか? select.selectedIndexは配列を受け入れるようには見えないので、これが私がそれを行うと考えることができる唯一の方法です。 Setを使用すると、毎回.includesを使用して配列をループするよりも効率的でなければなりません。

+0

'selectedOptions'は、選択されたオプションの要素のコレクションが含まれていますが、それは読み取り専用です。私はあなたが得たものが最良の方法かもしれないと思います。 – Barmar

+0

あなたの例では、オプション番号4も選択解除しています。 –

+1

私はいくつかのことを試してみましたが、ループを使用するのは約0.1ms以上と思われ、 'select.innerHTML'を約0.05msに設定し、' select.selectedIndex = 0; [2] .selected = trueを選択します。 [4] .selected = true約0.03 msを選択します。ハ! **重複して表示されたアイロニーが**複数の選択肢を効率的に** **効率的に複数選択するには – Slai

答えて

3

インデックス配列をループし、インデックスに一致するoptionsを更新します。

const select = document.getElementById('sel'); 
 
const indexes = [0, 2, 4]; 
 
// Clear the default selected 
 
select.selectedIndex = -1; 
 
// Select those indexes you want 
 
for(var idx of indexes){ 
 
    select[idx].selected = true 
 
}
<select id="sel" multiple size=5> 
 
    <option>one</option> 
 
    <option>two</option> 
 
    <option>three</option> 
 
    <option selected>four</option> 
 
    <option>five</option> 
 
</select>

+0

ああ...賢い。私は 'selectedIndex'を最初にリセットして既存の選択をクリアすることについては考えていませんでした。 – mpen

+0

待って...なんてことだ。 'select [2]'は3番目のオプションを返しますか? 'select.options [2]'を実行する必要はありませんか? – mpen

+1

はい。 MDNによると:https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/item –

関連する問題