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
How to convert all items (options) of a multi select dropdown into an array using jquery
提问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();
});
Edited针对@mellamokb 的评论进行了编辑,以修改 jQuery 以使用
text()
text()
而不是val()
val()
:var options = new Array();
$('#selectedItemLists > option:selected').each(
function(i){
options[i] = $(this).text();
});
References:
参考:
回答by Mark Coleman
回答by jimbo
The jQuery map
method is useful here.
jQuerymap
方法在这里很有用。
$('select option').map(function(index, elem){
return $(elem).text();
});
(Mark beat me to it, but mine uses the map
method of the collection rather than the "static" jQuery.map function. Both are fine, of course.)
(马克击败了我,但我使用了map
集合的方法而不是“静态”jQuery.map 函数。当然,两者都很好。)