我如何通过jQuery传递它的ID来获得一个选择的所有选项?

我只是想获取它们的值,而不是文本。


当前回答

$("#id option").each(function()
{
    $(this).prop('selected', true);
});

不过,正确的方法是设置元素的DOM属性,如下所示:

$("#id option").each(function(){
    $(this).attr('selected', true);
});

其他回答

捷径

$(() => {
$('#myselect option').each((index, data) => {
    console.log(data.attributes.value.value)
})})

or

export function GetSelectValues(id) {
const mData = document.getElementById(id);
let arry = [];
for (let index = 0; index < mData.children.length; index++) {
    arry.push(mData.children[index].value);
}
return arry;}
$("#id option").each(function()
{
    $(this).prop('selected', true);
});

不过,正确的方法是设置元素的DOM属性,如下所示:

$("#id option").each(function(){
    $(this).attr('selected', true);
});

我发现它既简短又简单,并且可以在Dev Tool控制台本身进行测试。

$ (" # id选项”)。Each ((index,element)=>console.log(index: ${index},值:${element. log)Value}, text: ${element.text})

如果您正在寻找一些选定文本的所有选项,那么下面的代码将工作。

$('#test').find("select option:contains('B')").filter(":selected");

另一种方法是使用toArray(),以便使用胖箭头函数与map,例如:

const options = $('#myselect option').toArray().map(it => $(it).val())