【发布时间】:2021-06-24 16:36:15
【问题描述】:
我正在尝试在本地存储中保存一些字符串,我正在尝试这样做,但我在本地存储中未定义。
我正在向用户询问玩家姓名,然后我想将它们存储在本地存储中以便再次使用它们。
这是我正在尝试的:
const x = localStorage.getItem('playersNum');
const parentDiv = document.getElementById('player-list');
for (let i = 0; i < x; i++) {
const newInput = document.createElement("INPUT");
newInput.setAttribute("type", "text");
newInput.setAttribute("class", "form-control");
newInput.setAttribute("id", `player${i}`);
newInput.setAttribute("placeholder", "Player's Name");
parentDiv.appendChild(newInput);
}
//get all input elements of type text and starting id with player
const input = document.querySelectorAll("[type='text'][id^='player']");
const btn = document.getElementById('startGame');
btn.addEventListener('click', function() {
//reset border style of all input elements
[...input].forEach(el => el.style.border = '');
//get all empty input elements
let empty = [...input].filter(el => el.value.trim() == "");
//check length
if (empty.length) {
//show alert
// alert('Please fill in the players names');
//set border style to empty input elements
empty.forEach(el => el.style.border = '1px solid red');
}
else {
window.location.assign('game.html');
localStorage.setItem('playersNames', String(input.value));
}
});
【问题讨论】:
标签: javascript html css twitter-bootstrap local-storage