如何使用localstorage将列表中的所有复选框布尔值存储到数组中

How to use localstorage to store all checkbox boolean values in a list to an array?

本文关键字:复选框 布尔值 存储 数组 localstorage 何使用 列表      更新时间:2023-09-26

代码如下:

<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 );
   }
});