保存到本地存储附加复选框状态

问题描述 投票:0回答:3

我具有此功能:

function test() {
    var a = document.getElementById('test');
    var b = document.createElement('input');
    b.type = 'checkbox';
    b.addEventListener( 'change', function() {
    if(this.checked) {
       //do something and save the state (checked)
    } else {
       //do something else and save the state(not checked)
    }
}

并且我想从附加的复选框中将复选框的状态保存在localstorage上,最好的方法是什么?

javascript checkbox append local-storage
3个回答
0
投票

因此,如果您要追加多个复选框,并且可能要分别设置其所有数据,则每个复选框都需要具有不同的ID,因此当您追加一个新复选框时,我会增加ID。


//function that appends new checkbox

var i = 0;
function appendCheckBox(){
    i++
    checkBoxId = 'checkbox' + i;
    document.getElementById('checkbox-container').innerHTML = `<input type="checkbox" id="${checkBoxId}" onclick="handleCheckBoxClick(this)"></input>`;
}

//function to handle checkbox click you would probably want to make it check if 
//the checkbox is already checked if it is set value to unchecked

function handleCheckBoxClick(ev){
    var checkBoxId = ev.id;
    localStorage.setItem(checkBoxId, 'checked')
}

0
投票

您可以使用:

设置存储:

localStorage.setItem('checkbox', b.checked);

获取存储空间:

var checkVal=localStorage.getItem('checkbox');

0
投票

您将需要做一些工作。localStoragedoesn't work in a snippet here,因此可以找到示例代码的工作示例@ this JSFiddle

localStorage.setItem("Checkboxes", "{}");
const showCurrentCheckboxStates = () => 
  document.querySelector("pre").textContent = `Checkboxes saved state ${
    JSON.stringify(JSON.parse(localStorage.getItem("Checkboxes")), null, " ")}`;
const saveCheckboxState = (val, id) => {
  localStorage.setItem("Checkboxes", 
      JSON.stringify({
        ...JSON.parse(localStorage.getItem("Checkboxes")),
        [`Checkbox ${id}`]: val })
      );
  showCurrentCheckboxStates();
};
const createCheckbox = id => {
  let cb = document.createElement('input');
  cb.type = 'checkbox';
  cb.dataset.index = id;
  cb.title = `Checkbox ${id}`;
  document.body.appendChild(cb);
  // save the initial state
  saveCheckboxState(0, id);
};

document.addEventListener("click", evt =>
  evt.target.dataset.index && 
    saveCheckboxState(+evt.target.checked, evt.target.dataset.index)
);

for (let i = 1; i < 11; i += 1) {
  createCheckbox(i);
}
© www.soinside.com 2019 - 2024. All rights reserved.