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

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


当前回答

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

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

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

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

其他回答

Use:

$("#id option").each(function()
{
    // Add $(this).val() to your list
});

.each() | jQuery API文档

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

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

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

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

$('#test').find("select option:contains('B')").filter(":selected");
$("input[type=checkbox][checked]").serializeArray();

Or:

$(".some_class[type=checkbox][checked]").serializeArray();

看看结果:

alert($("input[type=checkbox][checked]").serializeArray().toSource());

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

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