【问题标题】:Saving a couple of strings in the local storage在本地存储中保存几个字符串
【发布时间】: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


    【解决方案1】:

    您使用querySelectorAll 声明输入,因此您需要将输入作为数组读取。

    localStorage.setItem('playersNames', String(input[0].value));

    然后,如果你想要所有玩家的名字,你需要遍历数组。此外,您需要获取 localStorage 的先前值并附加到它,因为每次设置它都会被覆盖。

    const input = document.querySelectorAll("[type='text'][id^='player']");
    
    for (i=0; i < input.length; i++) {
    
        var checkForStorage = localStorage.getItem('playersNames');
    
      if (checkForStorage !== null) {
            localStorage.setItem('playersNames', checkForStorage + ',' + String(input[i].value))  
      } else {
            localStorage.setItem('playersNames', String(input[i].value));
      }
    };
    

    【讨论】:

    • 感谢您的回复,当我这样做时,我只得到第一个玩家的名字,我想存储所有玩家的名字。
    • 我已经更新了我原来的答案,希望对你有帮助!
    • 谢谢,当我使用这段代码时,我得到 (playersNames ,,,)
    猜你喜欢
    • 2013-09-02
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 2017-07-13
    • 2021-09-10
    • 2012-06-19
    • 1970-01-01
    • 2013-04-21
    相关资源
    最近更新 更多