javascript 使用 querySelectorAll 获取选定的选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15586577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:18:13  来源:igfitidea点击:

Getting selected options with querySelectorAll

javascripthtml-selectselectors-api

提问by GOTO 0

I wonder if it's possible in Javascript to get the currently selected options in a <select multiple>field using the Selctors API rather than a "stupid" iteration over all options.

我想知道是否有可能在 Javascript 中<select multiple>使用 Selctors API 而不是所有选项的“愚蠢”迭代来获取字段中当前选择的选项。

select.querySelectorAll('option[selected="selected"]')only returns the options that were marked as preselected in the original HTML, which is not what I'm looking for. Any ideas?

select.querySelectorAll('option[selected="selected"]')只返回在原始 HTML 中标记为预选的选项,这不是我要找的。有任何想法吗?

回答by a better oliver

document.querySelectorAll('option:checked')

document.querySelectorAll('option:checked')

Works even on IE9 ;)

即使在 IE9 上也能工作;)

回答by Daniel Imms

I was also experienced your issue, I have a feeling it's to do with JavaScript not recognising changes in the DOM.

我也遇到过您的问题,我感觉这与 JavaScript 无法识别 DOM 中的更改有关。

Here is a solution:

这是一个解决方案:

jsFiddle

js小提琴

document.getElementById('test').onclick = function () {
    var select = document.getElementById('select');
    var options = getSelectedOptions(select);
    console.log(options);
};

function getSelectedOptions(select) {
    var result = [];
    var options = select.getElementsByTagName('option');
    for (var i = 0; i < options.length; i++) {
        if (options[i].selected)
            result.push(options[i]);
    };
    return result;
}