【发布时间】:2021-05-07 01:33:25
【问题描述】:
我已经设法将用户的多个输入存储到数组中的localStorage 中,现在我需要在点击时随机显示输入。所以基本上有人只是不断地点击一个“生成”按钮来随机和单独地查看每个输入。我需要让它以随机和单独的方式显示从 localstorage(或 elswhere)存储在数组中的内容。可能在文本区域中旋转。
目前我让它一次显示而不是单独显示。非常感谢任何和所有帮助。
<form>
<input id="item" type="text" placeholder="Add New Favorite Here" >
</form>
<div id="favul"><ul id="items"></ul></div>
<button id="favbutton1" style="width:100px" onclick="wipe()">Clear</button>
<script>
const form = document.querySelector('form');
const ul = document.querySelector('ul');
const input = document.getElementById('item');
let itemsArray = localStorage.getItem('items') ? JSON.parse(localStorage.getItem('items')) : [];
localStorage.setItem('items', JSON.stringify(itemsArray));
const data = JSON.parse(localStorage.getItem('items'));
const liMaker = (text) => {
const li = document.createElement('li');
li.textContent = text;
ul.appendChild(li);
}
form.addEventListener('submit', function (e) {
e.preventDefault();
itemsArray.push(input.value);
localStorage.setItem('items', JSON.stringify(itemsArray));
liMaker(input.value);
input.value = "";
});
data.forEach(item => {
liMaker(item);
});
function wipe() {
localStorage.clear();
while (ul.firstChild) {
ul.removeChild(ul.firstChild);
}
itemsArray = [];
};
</script>
<button id="favButton" onclick="copy()">Copy</button><br>
<script>
function copy() {
let plot = document.getElementById("plot");
plot.select();
document.execCommand("copy");
}
</script>
【问题讨论】:
-
你的代码在哪里?您的具体问题是什么?您是否尝试过解决方案?请阅读How to ask a question?
-
请您分享一个minimal reproducible example 的问题?
-
请原谅我的无知,但每当我尝试放置代码段时,它都会呈现错误
-
很丑,我知道
-
添加代码时,如果缩进4个空格,会自动渲染为代码。或者,您可以正常输入,然后选择它并单击编辑器工具栏上的
{}按钮,这将为您进行缩进。您还可以单击<>按钮在堆栈 sn-p 编辑器中创建代码的可执行版本。
标签: javascript html arrays random local-storage