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

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


当前回答

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

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

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

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

其他回答

这将把#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())
$("input[type=checkbox][checked]").serializeArray();

Or:

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

看看结果:

alert($("input[type=checkbox][checked]").serializeArray().toSource());
$('select#id').find('option').each(function() {
    alert($(this).val());
});

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

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

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

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

对于多选选项:

$('#test').val()返回所选值列表。 $(" #测试选项”)。Length返回选项总数(包括选中的和未选中的)