如何使用localstorage将列表中的所有复选框布尔值存储到数组中
How to use localstorage to store all checkbox boolean values in a list to an array?
代码如下:
<div id="list">
<input type="checkbox" id="1">
<input type="checkbox" id="2">
<input type="checkbox" id="3">
</div>
在另一个html窗格(一个单独的模板)中,我想将所有这些复选框(checked
/unchecked
)布尔值存储到数组中。我所做的看起来像:
var array = [];
var checkboxli = document.getElementsByTagName("input");
for (var i = 0; i < checkboxli.length; i++)
{
array.push($("#input.prop('checked')"));
}
然而,这不起作用。我有其他模板使用标签名称"input
",所以我需要将标签名称限制为"#list"
id下的标签名称(也许是某种css选择器)。目前,document.getElementsByTagName("input")
和$("#input.prop('checked')")
都不能工作。可能还有其他语法问题。请帮我解决。谢谢。
[true, false, true, true, true...]
,其中每个布尔值表示是否选中相应的输入复选框
既然你已经在使用jquery了,你可以这样做:
假设这个HTML
<div id="list">
<input type="checkbox" id="1" checked="checked">
<input type="checkbox" id="2">
<input type="checkbox" id="3" checked="checked">
</div>
和这个脚本:
var array = [];
$("input[type='checkbox']","#list").each(function(){
array.push($(this).is(":checked"));
});
你会得到像这样的东西:
array = [ true, false, true ];
而不是:
var checkboxli = document.getElementsByTagName("input");
可以使用:
var checkboxli = document.querySelectorAll("#list>input[type=checkbox]"); //array of checkboxes
现在列表元素下有了所有的复选框。
如果你只想要选中的复选框,你可以使用:
var checkboxli = document.querySelectorAll("#list>input[type=checkbox][checked]");
试试下面的代码。它从所有checked
check-boxes
中检索所有IDs
,存储在array
中,然后将local-storage
存储为string
:
var itemsChecked = [] ;
$('input[type=checkbox]:checked').each(function(index, item){
itemsChecked.push($(item).attr('id'));
})
localStorage.setItem('selectedItems', JSON.stringify(itemsChecked));
之后,要从本地存储中检索数据,请使用以下命令:
var items = JSON.parse(localStorage.getItem('selectedItems'));
// returns array of IDs
更合适的方法是从正文开始捕获每个元素的XPath。你可以使用getPath jQuery插件,这样你就不会像List那样依赖于一个特定的字符串。
jQuery.fn.extend({
getPath: function( path ) {
// The first time this function is called, path won't be defined.
if ( typeof path == 'undefined' ) path = '';
// If this element is <html> we've reached the end of the path.
if ( this.is('html') )
return 'html' + path;
// Add the element name.
var cur = this.get(0).nodeName.toLowerCase();
// Determine the IDs and path.
var id = this.attr('id'),
class = this.attr('class');
// Add the #id if there is one.
if ( typeof id != 'undefined' )
cur += '#' + id;
// Add any classes.
if ( typeof class != 'undefined' )
cur += '.' + class.split(/['s'n]+/).join('.');
// Recurse up the DOM.
return this.parent().getPath( ' > ' + cur + path );
}
});
相关文章:
- 检查数据库中复选框的值
- 以编程方式添加的复选框的值
- 通过原型/构造函数从复选框输出值
- 获取文本框中所有选定复选框的值
- 如何对选定的复选框行值求和
- 通过 JQuery 获取单击的复选框的值属性
- 使用 onChange 属性以内联方式更改复选框的值
- 获取 ajax 创建的复选框的值
- 获取 JavaScript 中复选框的值
- 普通获取选中复选框的值
- 如何获取切换复选框的值
- 根据MVC列表框和复选框的值更改标记元素
- 使用 Javascript 提取复选框的值
- 如何提交未选中复选框的值
- <JSP>正在获取复选框的值
- 使用angularjs中复选框的值更新数组
- 获取所选复选框的值和文本
- 为什么我的localStorage复选框/布尔值比较不适用于我的Google Chrome扩展
- 如何使用localstorage将列表中的所有复选框布尔值存储到数组中
- 如何使用Angular Schema Form复选框布尔值处理onChange