【问题标题】:How to count number of option tags using jQuery?如何使用 jQuery 计算选项标签的数量?
【发布时间】:2011-04-09 00:44:01
【问题描述】:

我有一个问题,当我有多个具有相同类和 id 的选择框时,如何计算选项标签的数量?

假设我有三个选择框。而且我想要选择框的大小,以便我可以动态添加具有相同选项的新选择框:

<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>

【问题讨论】:

标签: jquery html count html-select


【解决方案1】:

使用 jquery:

对于给定的selectid

$('select#selectid option').length

对于所有具有给定类的selects

$('select.selectclass option').length

对于页面中的所有selects

$('select option').length

但您应该为 html 页面中的每个元素提供不同的 ID

【讨论】:

  • 不..它给了我选项标签的倍数..对于上面的例子它返回 6。但我需要 2 作为我的答案。
  • 因为您为所有选择提供了相同的 id
  • @mad_programmer:停止错误地使用 ID,这不会成为问题。
  • 如果您使用的是 fisrt 选项(带有 ids),请不要删除 ids。只需提供不同的 id(selectid1、selectid2、selectid3)并用您选择的 id 替换 #selectid。例如,如果您希望使用 id='select1' 选择选项计数 -> 使用 $('select#select1 option').length
  • 谢谢,在类似情况下帮助了我。
【解决方案2】:

标签 ID 应该对文档是唯一的。您是否打算同时在文档树中包含所有这些内容?

【讨论】:

    【解决方案3】:

    我发现使用 JQuery children() 方法得到了更一致的结果,即,

    $('.productDetail_variant select').each(function() {
          var currSelectValue = $(this).children();
          alert(currSelectValue.length);
    });
    

    【讨论】:

    • 万一其他人发现这个并认为'哦,这是一个很好的解决方案',它不是。一个 select 元素记住也可以有 optgroups 这会使长度错误。
    • 这对我有用,而不是使用 optgroups。顺便说一下,将“选项”指定为子项可以解决 optgroups 问题。在 Chrome 中,当我尝试 size 或 length 时,无论如何我总是得到 1。干得好!这是 1 班轮: $('#select_id').children('option').length
    猜你喜欢
    • 2012-07-31
    • 2019-10-26
    • 2023-03-16
    • 2011-08-10
    • 2011-01-11
    • 2011-03-15
    • 2018-11-04
    • 2011-02-15
    • 1970-01-01
    相关资源
    最近更新 更多