如何在本地存储中保存多个点击计数器?

时间:2019-11-03 10:53:10

标签: javascript

我有几个计数器,如何将所有值存储在商店中?在这个例子中甚至有可能吗?

我在此处创建了一个代码段:

document.addEventListener('click', function(event) {
  if (event.target.dataset.counter != undefined) {
    event.target.value++;
  }
});
Counter: <input type="button" value="1" data-counter> 
Another counter: <input type="button" value="2" data-counter> 
And another counter: <input type="button" value="2" data-counter>

3 个答案:

答案 0 :(得分:0)

document.addEventListener('click', function(event) {
  if (event.target.dataset.counter != undefined) {
    event.target.value++;
    window.localStorage.setItem(event.target.name, event.target.value);
  }
});
Counter: <input type="button" value="1" name="counter1" data-counter> Another counter: <input type="button" value="2" name="counter2" data-counter> And another counter: <input type="button" value="2" name="counter3" data-counter>

单击时使用localStorage.setItem函数对其进行缓存。

答案 1 :(得分:0)

您可以给按钮ID并使用一个对象将值存储为键值对(其中每个键是与按钮对应的ID)。然后,当您从bottomNavigationBar: BottomAppBar( color: Colors.blue, child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ IconButton( icon: Icon(Icons.home), onPressed:(){ Navigator.push(context,MaterialPageRoute(builder: (context) => mainmenu())); }, ), IconButton( icon: Icon(Icons.send), onPressed: (){ sendEmail(); } ) ], ), ), 存储和检索该对象时,可以使用JSON.stringify()JSON.parse()

localStorage在堆栈片段中不起作用,see this codepen是一个工作示例。

localStorage

答案 2 :(得分:0)

一种解决方法是在内存中设置一个对象,然后在更新任何计数器时更新该对象。

工作示例:

// Grab dataCounter Buttons
const dataCount = document.getElementsByClassName('data-count')[0];
const dataCounters = [... document.querySelectorAll('[data-counter]')];

// Initialise dataCountObject
let dataCountObject = {};
dataCounters.forEach((dataCounter, i) => {
  dataCountObject['dataCounter' + i] = parseInt(dataCounter.value);
});
console.log(dataCountObject);

// Increment both dataCounter and dataCountObject
const incrementCount = (event) => {

  if (event.target.dataset.counter != undefined) {
  
    let index = dataCounters.indexOf(event.target);
    dataCountObject['dataCounter' + index]++;
    event.target.value++;
    console.log(dataCountObject);
  }
}

// Attach Event Listener to dataCount
dataCount.addEventListener('click', incrementCount, false);
<form class="data-count">
<label>Counter: <input type="button" value="1" data-counter></label>
<label>Another counter: <input type="button" value="2" data-counter> </label>
<label>And another counter: <input type="button" value="2" data-counter></label>
</form>

然后,如果您想随时保存到localStorage,则可以使用以下方法将对象序列化为字符串:

let dataCountJSON = JSON.stringify(dataCountObject);

,然后您可以将JSON字符串添加到localStorage

localStorage.setItem('dataCount', 'dataCountJSON');