【问题标题】:How to store an attribute of all input(checkbox) elements in Javascript?如何在Javascript中存储所有输入(复选框)元素的属性?
【发布时间】:2011-01-06 16:44:28
【问题描述】:

我正在尝试将页面中所有复选框的 name 属性存储在某种数组/数据结构中。

我该怎么做?

<input name="sample" type="checkbox" value="" align="left" />
<input name="sample2" type="checkbox" value="" align="left" />

名称属性将是唯一的。对如何进行此操作有任何想法吗?

【问题讨论】:

    标签: javascript jquery data-structures elements


    【解决方案1】:

    您可以使用.map() 获取一组元素的属性并将其放入数组中,如下所示:

    var arr = $("input[type=checkbox]").map(function() { return this.name; }).get();
    

    有更纤细的选择器,例如 input:checkbox 甚至 :checkbox,但它们要慢得多

    【讨论】:

      【解决方案2】:
      var store_them_here = [];
      $(':checkbox').each(function(i, e) {
          store_them_here.push($(e).attr('name'));
      })
      

      【讨论】:

      • 很有趣,如果上述方法不起作用,我将使用它。谢谢!
      【解决方案3】:

      试试

      var result_array = [];
      jQuery(':checkbox').each( function(index, Element){
        result_array.push(jQuery(this).attr('name'));
      })
      

      【讨论】:

        猜你喜欢
        • 2013-09-09
        • 2019-12-24
        • 2011-04-07
        • 2012-04-04
        • 2018-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多