简体   繁体   English

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

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

The code looks like this: 代码如下:

<div id="list">
  <input type="checkbox" id="1">
  <input type="checkbox" id="2">
  <input type="checkbox" id="3">
</div>

In another html pane (a separate template), I want to store all those checkbox ( checked / unchecked ) booleans into an array. 在另一个HTML窗格(一个单独的模板)中,我要将所有这些复选框( checked / unchecked )布尔值存储到一个数组中。 What I did looks like: 我所做的看起来像:

var array = [];
var checkboxli = document.getElementsByTagName("input");
for (var i = 0; i < checkboxli.length; i++)
{
  array.push($("#input.prop('checked')"));
}

However, this doesn't work. 但是,这不起作用。 I have other templates using tag name " input ", so I need to limit the tag name to the ones under "#list" id (some sort of css selector perhaps). 我还有其他使用标签名称“ input ”的模板,因此我需要将标签名称限制为"#list" ID(可能是某种CSS选择器)下的标签名称。 Currently, both document.getElementsByTagName("input") and $("#input.prop('checked')") won't work. 目前, document.getElementsByTagName("input")$("#input.prop('checked')")无法使用。 There might be other syntax problems. 可能还有其他语法问题。 Please help me resolve. 请帮我解决。 Thanks. 谢谢。

EDIT: It seems like I didn't communicate my intention well. 编辑:看来我没有很好地传达我的意图。 Here is what I want to get out of the list: An array that looks like 这是我想从列表中删除的内容:一个看起来像的数组

[true, false, true, true, true...]

in which each boolean value represents whether the corresponding input checkbox is checked or not. 其中每个布尔值表示是否选中了相应的输入复选框。

Since your are already using jquery, you can go like this: 由于您已经在使用jquery,因此可以这样进行:

Assuming this HTML 假设这个HTML

<div id="list">
  <input type="checkbox" id="1" checked="checked">
  <input type="checkbox" id="2">
  <input type="checkbox" id="3" checked="checked">
</div>

And this script: 这个脚本:

var array = [];
$("input[type='checkbox']","#list").each(function(){
     array.push($(this).is(":checked"));
});

You would get something like this: 您将获得如下内容:

array = [ true, false, true ];

Instead of: 代替:

var checkboxli = document.getElementsByTagName("input");

you can use: 您可以使用:

var checkboxli = document.querySelectorAll("#list>input[type=checkbox]"); //array of checkboxes

now you have all of the checkboxes under the list element. 现在,您具有所有在list元素下的复选框。

if you want only the checked checkboxes you can use: 如果只需要选中的复选框,则可以使用:

var checkboxli = document.querySelectorAll("#list>input[type=checkbox][checked]"); 

Try below code. 尝试下面的代码。 It retrieves all IDs from all checked check-boxes , stores in an array and then stores in local-storage as an string : 它从所有checked check-boxes检索所有IDs ,存储在array ,然后作为string存储在local-storage中:

var itemsChecked = [] ;
$('input[type=checkbox]:checked').each(function(index, item){
   itemsChecked.push($(item).attr('id'));
})

localStorage.setItem('selectedItems', JSON.stringify(itemsChecked));

Later, to retrieved data from localstorage, use the following: 以后,要从本地存储中检索数据,请使用以下命令:

var items = JSON.parse(localStorage.getItem('selectedItems')); 
// returns array of IDs

A more suitable approach would be to capture the XPath of each element starting from the body. 一种更合适的方法是从主体开始捕获每个元素的XPath。 You could use a getPath jQuery plugin, Thus you won't be dependent upon a specific string like the List. 您可以使用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 );
   }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM