如何使用 jQuery 计算选项标签的数量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5602099/
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 count number of option tags using jQuery?
提问by Maverick
I have a question as to how can I calculate number of options tag when I have multiple select box with same class and id?
我有一个问题,当我有多个具有相同类和 ID 的选择框时,如何计算选项标签的数量?
Let's say I have three select boxes. And I want the size of select box, so that I can dynamically add new select box with the same options:
假设我有三个选择框。我想要选择框的大小,以便我可以动态添加具有相同选项的新选择框:
<select id="selectid" class="selectclass">
<option>1</option>
<option>2</option>
</select>
<select id="selectid" class="selectclass">
<option>1</option>
<option>2</option>
</select>
<select id="selectid" class="selectclass">
<option>1</option>
<option>2</option>
</select>
回答by manji
with jquery:
使用 jquery:
for a given select
with an id
:
对于一个给定select
的id
:
$('select#selectid option').length
for all selects
with a given class:
对于所有selects
给定的类:
$('select.selectclass option').length
for all selects
in the page:
对于selects
页面中的所有内容:
$('select option').length
but you should give different Ids to each element in a html page
但是您应该为 html 页面中的每个元素提供不同的 Id
回答by James
Tag IDs are supposed to be unique to a document. Do you plan to have all of these in the document tree at the same time?
标签 ID 应该是文档唯一的。您是否打算同时在文档树中包含所有这些内容?
回答by Si Davies
I found that I got more consistent results using the JQuery children()
method, i.e.,
我发现我使用 JQuerychildren()
方法得到了更一致的结果,即,
$('.productDetail_variant select').each(function() {
var currSelectValue = $(this).children();
alert(currSelectValue.length);
});