【问题标题】: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'));
})