javascript jquery从JSON数组中的选择框中收集所有选项值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9258080/
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
jquery collect all option values from select box in a JSON array
提问by Vineet
I have a select box.
我有一个选择框。
<select id='x'>
<option value='1'>'Vineet'</option>
<option value='2'>'Vivek'</option>
<option value='3'>'Madhu'</option>
</select>
The options are added dynamically to it. At the end, I want to collect the values of ALL option elements contained within this select box into an array. I searched the forum for the answer, but Q/A are there for getting the 'selected' option only.
选项是动态添加的。最后,我想将此选择框中包含的所有选项元素的值收集到一个数组中。我在论坛上搜索了答案,但 Q/A 仅用于获取“已选择”选项。
I tried this:
我试过这个:
var myList = [];
$('#x').each(function() { myList.push( $(this).value() ) });
In firebug, It gives this error:
在萤火虫中,它给出了这个错误:
missing } after property list
属性列表后缺少}
But I fail to see any missing }
. What am I doing wrong here?
但我没有看到任何遗漏}
。我在这里做错了什么?
回答by Rory McCrossan
You need to loop through each option
element within the select, not just the select itself, also, the correct method to get the value of an input in jQuery is val()
, try this:
您需要遍历option
选择中的每个元素,而不仅仅是选择本身,而且,在 jQuery 中获取输入值的正确方法是val()
,试试这个:
myList = [];
$('#x option').each(function() {
myList.push($(this).val())
});
You can also use map()
:
您还可以使用map()
:
var myList = $('#x option').map(function() {
return this.value;
}).get();
In both cases, the myList
variable will contain an array of strings.
在这两种情况下,myList
变量都将包含一个字符串数组。
回答by Anthony Grist
Try jQuery function for getting the value of an element (wrapped in a jQuery object) is .val()
, not .value()
- that may be causing some confusion, though I can't be sure.
尝试使用 jQuery 函数获取元素的值(包装在 jQuery 对象中) is .val()
,而不是.value()
- 这可能会引起一些混乱,尽管我不能确定。
As a side note, your selector is incorrect for what you want. $('#x')
will return all of the elements that have an id
of x
- which should only ever be one element - then the .each()
will iterate over that set of elements (so it will call the function once). You'll just end up with an array that contains a single value, which will be the currently selected value of the <select>
input.
作为旁注,您的选择器不适合您的需求。$('#x')
将返回所有具有一个要素id
的x
-这应该永远只能是一个元素-那么.each()
会遍历该集合的元素(所以它会调用一次函数)。您将最终得到一个包含单个值的数组,该值将是<select>
输入的当前选定值。
Instead, use $('#x > option')
which will return all <option>
elements that are immediate children of the <select>
element with the id
of x
.
相反,使用$('#x > option')
这将返回所有<option>
属于的直接子元素<select>
与元素id
的x
。