JQuery:遍历多个 <select> 元素中的所有 <option> 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15014663/
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 : Iterate through all <option> elements in a multiple <select> element
提问by iJared
I have a multiple element as follows:
我有一个多元素如下:
<select id="mySelect" multiple>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
I want to iterate through this multiple select list and read the values of all the options. I have this JQuery on another page that iterates through all the selected options in a multiple select element like this:
我想遍历这个多选列表并读取所有选项的值。我在另一个页面上有这个 JQuery,它遍历多个选择元素中的所有选定选项,如下所示:
$('#mySelect option:selected').each(function(){ ... });
How do I modify the above statement so that the .each will return all of the options one by one instead of only those that are selected?
如何修改上述语句,以便 .each 将一一返回所有选项,而不是仅返回选定的选项?
I tried these:
我试过这些:
$('#mySelect option').each(function(){ ... });
$('#mySelect option').children().each(function(){ ... });
$('#mySelect option').children(function(){ ... });
$('#mySelect > option').each(function(){ ... });
but none worked.
但没有一个工作。
EDIT: Sorry everyone the typo was in my first statement on here then I copy/pasted it 4x's. In my actual code the # is there but it does not work.
编辑:对不起,每个人的错字都出现在我在这里的第一条语句中,然后我复制/粘贴了 4 次。在我的实际代码中,# 在那里,但它不起作用。
UGGHHH LOL the error isn't with my JQuery but with my html select element. I was using the name attribute instead of id.
UGGHHH LOL 错误不是与我的 JQuery 而是与我的 html select 元素有关。我使用的是 name 属性而不是 id。
回答by Blender
Your selector is missing a #
:
您的选择器缺少一个#
:
$('#mySelect option').each(function(){ ... });
^
Without the #
, you look for <mySelect>
elements.
如果没有#
,您将查找<mySelect>
元素。
回答by Roko C. Buljan
回答by Abe Miessler
Change it to this:
改成这样:
$('#mySelect option')
right now you have it as this:
现在你有它:
$('mySelect option')
which is looking for an element of type mySelect
. The # specifies that you are matching IDs
它正在寻找类型为 的元素mySelect
。# 指定您正在匹配 ID