簡體   English   中英

從 localstorage 中的數組中獲取項目並使用按鈕單獨顯示它們

[英]Get items from an array in localstorage and display them each individually using a button

我已經設法將用戶的多個輸入存儲到數組中的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>

如果我沒有弄錯,隨機數字生成器將解決您的問題。 您可以簡單地鏈接您的按鈕和(0,數組長度)之間的數字生成器 function。 這是用python編寫的簡單偽代碼。

import random

your_array = [...]

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM