javascript 如何使用 jquery 将多选下拉列表的所有项目(选项)转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5983920/
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-25 19:02:24  来源:igfitidea点击:

How to convert all items (options) of a multi select dropdown into an array using jquery

javascriptjqueryhtml

提问by Satya

I am trying to convert a multiple select dropDown values (all options) into an array using jquery.

我正在尝试使用 jquery 将多个选择下拉值(所有选项)转换为数组。

<select size="10" style="width: 330px;" name="itemList"
        id="selectedItemLists" multiple="multiple">
    <option value="1">value1</option>
    <option value="2">value2</option>
    <option value="3">value3</option>
    <option value="4">value4</option>
</select>

Now using jquery how to create an array like array[0]=value1,array[1]=value2...

现在使用 jquery 如何创建一个数组,如 array[0]=value1,array[1]=value2...

Please help me in this.

请帮助我。

Thanks in advance.

提前致谢。

回答by David says reinstate Monica

Possibly something like:

可能是这样的:

var options = new Array();
$('#selectedItemLists > option:selected').each(
     function(i){
         options[i] = $(this).val();
     });

JS Fiddle demo.

JS小提琴演示



Edited针对@mellamokb 的评论进行了编辑,以修改 jQuery 以使用text()text()而不是val()val()

var options = new Array();
$('#selectedItemLists > option:selected').each(
     function(i){
         options[i] = $(this).text();
     });

JS Fiddle demo.

JS小提琴演示

References:

参考:

回答by Mark Coleman

You can use .map()to accomplish this as well.

您也可以使用它.map()来完成此操作。

var i = $.map($("#selectedItemLists option:selected"), function(elem){
    return $(elem).text();
});

Example on jsfiddle

jsfiddle 示例

回答by jimbo

The jQuery mapmethod is useful here.

jQuerymap方法在这里很有用。

$('select option').map(function(index, elem){
    return $(elem).text();
});

(Mark beat me to it, but mine uses the mapmethod of the collection rather than the "static" jQuery.map function. Both are fine, of course.)

(马克击败了我,但我使用了map集合的方法而不是“静态”jQuery.map 函数。当然,两者都很好。)