【问题标题】:Get items from an array in localstorage and display them each individually using a button从 localstorage 中的数组中获取项目并使用按钮单独显示它们
【发布时间】: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个空格,会自动渲染为代码。或者,您可以正常输入,然后选择它并单击编辑器工具栏上的{} 按钮,这将为您进行缩进。您还可以单击&lt;&gt; 按钮在堆栈 sn-p 编辑器中创建代码的可执行版本。

标签: javascript html arrays random local-storage


【解决方案1】:

如果我没有弄错,随机数字生成器将解决您的问题。您可以简单地链接您的按钮和(0,数组长度)之间的数字生成器函数。这是用python编写的简单伪代码。

import random

your_array = [...]

def press_button(list):
    return your_array(random.randint(0, len(list)))

【讨论】:

  • 该问题未使用 Python 标记。
  • 感谢您的努力,但 Python 无法在这里工作
猜你喜欢
  • 1970-01-01
  • 2022-11-01
  • 1970-01-01
  • 2017-11-13
  • 1970-01-01
  • 2017-10-13
  • 1970-01-01
  • 2021-09-26
  • 2012-03-25
相关资源
最近更新 更多