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

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


当前回答

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

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

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

其他回答

有些答案使用这两种方法,但恕我直言,地图是更好的选择:

$("select#example option").map(function() {return $(this).val();}).get();

jQuery中有(至少)两个地图函数。Thomas Petersen的答案是“Utilities/jQuery.map”;这个答案使用了“遍历/映射”(因此代码更简洁)。

这取决于你要如何处理这些值。如果你想从函数中返回值,map可能是更好的选择。但是,如果您打算直接使用这些值,则可能需要每个值。

$("select#MY_SELECT_ID").find('option').each(function() {
    console.log($(this).val());
    console.log($(this).text());
});

美元。地图可能是最有效的方法。

var options = $('#selectBox option');

var values = $.map(options ,function(option) {
    return option.value;
});

如果你只想要那些被选中的选项,你可以在$('#selectBox option:selected')中添加更改选项。

第一行选择所有复选框,并将其jQuery元素放入变量中。然后,我们使用jQuery的.map函数对该变量的每个元素应用一个函数;我们所做的只是返回每个元素的值,因为这是我们所关心的。因为我们是在map函数内部返回它们,它实际上会根据请求构建一个值的数组。

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

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

这将把#myselectbox的选项值放入一个整洁的数组中:

// First, get the elements into a list
var options = $('#myselectbox option');

// Next, translate that into an array of just the values
var values = $.map(options, e => $(e).val())