简体   繁体   English

向 localStorage 添加多个值,然后在 JavaScript 中随机检索一个

[英]Add multiple values to localStorage and then retrieve a random one in JavaScript

I am trying to make a system where the user inputs multiple values at separate times and then can click a button that tells them one of their inputs (at random).我正在尝试制作一个系统,其中用户在不同的时间输入多个值,然后可以单击一个按钮,告诉他们其中一个输入(随机)。 This is what I have so far:这是我到目前为止:

(Note: for some odd reason this code snippet is not functioning properly here (at least not on my side) but it is working just fine in JS Bin and even my own Notepad++) (注意:由于某些奇怪的原因,这段代码片段在这里无法正常运行(至少在我这边不是),但它在 JS Bin 甚至我自己的 Notepad++ 中都运行良好)

 function store(){ var toStore = document.getElementById("itemInputBox"); localStorage.setItem("itemInputBox", toStore.value); } function get(){ var toGet = localStorage.getItem("itemInputBox"); document.getElementById("outputArea").innerHTML = toGet; }
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <form id="itemForm"> <input type="text" id="itemInputBox" autocomplete="off" onmouseout="store()"><br><br> <button id="getStoredValue" onclick="get()" type="button" style="cursor:pointer;">Get Input Value</button> </form> <div id="outputArea"></div> </body> </html>

As I am fairly new to coding (have been doing it for only a year or so) and I am also new to localStorage, I need some guidance for this.由于我对编码相当陌生(只做了一年左右)而且我也是 localStorage 的新手,因此我需要一些指导。 Thanks to whoever responds!感谢回答的人!

You can use an array to store your values您可以使用数组来存储您的值
Before you add a new value you'll have to retrieve the array from local storage在添加新值之前,您必须从本地存储中检索数组
Add the new value to the array and replace the previous array in local storage with the updated one将新值添加到数组并用更新的数组替换本地存储中的前一个数组
Use JSON to serialize the data to store it in local storage If there is no data in local storage create an array with the value使用 JSON 序列化数据存储在本地存储 如果本地存储中没有数据,则使用该值创建一个数组

For the get functionality, after you retrieve the array you can generate a random number from 0 to the length of the array-1 to choose a value by index.对于获取功能,检索数组后,您可以生成一个从 0 到数组长度的随机数 - 1 以按索引选择值。

You can use Arrays in Javascript to store multiple values in the localStorage.您可以在 Javascript 中使用数组在 localStorage 中存储多个值。 When storing the values, they should be in JSON format.存储值时,它们应该采用 JSON 格式。 Also, when retrieving the values you have to pass that JSON string to `JSON.parse(array) and then retrieve the values.此外,在检索值时,您必须将该 JSON 字符串传递给 `JSON.parse(array),然后检索值。

To get a random value from that array, you can use Math functions in JavaScript.要从该数组中获取随机值,您可以在 JavaScript 中使用 Math 函数。 Please check the example below.请检查下面的示例。 It won't work in the StackOverflow code snippets section because it restricts the LocalStorage functions but you can check it locally.它在 StackOverflow 代码片段部分不起作用,因为它限制了 LocalStorage 功能,但您可以在本地检查它。

 function store(){ var toStore = document.getElementById("itemInputBox"); var valuesJSON = get(); if (valuesJSON == null){ createLocalStorageKey(); } var values = JSON.parse(get()); values.items.push(toStore.value); localStorage.setItem("itemInputBox", JSON.stringify(values)); } function createLocalStorageKey(){ localStorage.setItem("itemInputBox", JSON.stringify({items:[]})); } function get(){ var toGet = localStorage.getItem("itemInputBox"); return toGet; } function parseValueToHTML(){ var valuesJSON = get(); if (valuesJSON == null){ createLocalStorageKey(); } var values = JSON.parse(get()); document.getElementById("outputArea").innerHTML = values.items[Math.floor(Math.random() * values.items.length)]; }
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <form id="itemForm"> <input type="text" id="itemInputBox" autocomplete="off"><br><br> <button onclick="store()" type="button">Store Value</button> <button id="getStoredValue" onclick="parseValueToHTML()" type="button" style="cursor:pointer;">Get Input Value</button> </form> <div id="outputArea"></div> </body> </html>

my way...我的方式...

 const itemForm = document.forms['item-form'] , getAllItems = _ => { let r = localStorage.getItem('itemInputBox') return !r ? [] : JSON.parse(r) } , setAllItems = arr => { localStorage.setItem('itemInputBox',JSON.stringify(arr)) } ; itemForm.setValueStored.onclick=()=> { let val = itemForm.itemInputBox.value.trim() if (val) { let store = getAllItems() if (!store.include(val)) { store.push(val) setAllItems(store) } } itemForm.itemInputBox.value = '' } itemForm.getStoredValue.onclick=()=> { let store = getAllItems() itemForm.itemInputBox.value = (!store.length) ? '' : store[Math.floor(Math.random() *store.length)] }
 <form name="item-form"> <input type="text" name="itemInputBox" autocomplete="off"> <br><br> <button name="setValueStored" type="button">Set value in store</button> <button name="getStoredValue" type="button">Get random input value from store</button> </form>

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

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