簡體   English   中英

推送 function 無法正常工作 localStorage Javascript vanilla

[英]Push function is not working properly localStorage Javascript vanilla

我正在做一個點擊時間游戲,你可以想象最快的時間將是第一位的。 我只想得到3分。 並將其保存在本地存儲中,但每次我開始新游戲時,實際分數都會重置其值,並且不會產生其他分數。 3 個分數的值應為 0。我嘗試將它們推為 arrays 但推 function 效果不佳。 在這一點上,我被困住了。 我不知道該怎么辦。 如果你能幫助我,我將不勝感激,謝謝!

let times = Array.from({
  length: 3
})


let interval2;

// Timer CountUp
const timerCountUp = () => {
  let times = 0;
  let current = times;

  interval2 = setInterval(() => {
    times = current++
    saveTimes(times)
    return times
  }, 1000);
}

// Saves the times to localStorage
const saveTimes = (times) => {
  localStorage.setItem('times', JSON.stringify(times))
}


// Read existing notes from localStorage
const getSavedNotes = () => {
  const timesJSON = localStorage.getItem('times')

  try {
    return timesJSON ? JSON.parse(timesJSON) : []
  } catch (e) {
    return []
  }
}

//Button which starts the countUp
start.addEventListener('click', () => {
  timerCountUp();
})

// Button which stops the countUp
document.querySelector('#start_button').addEventListener('click', (e) => {
  console.log('click');
  times.push(score = interval2)
  getSavedTimes()

  if (interval) {
    clearInterval(interval);
    clearInterval(interval2);
  }
})

這個:

// Button which stops the countUp
document.querySelector('#start_button').addEventListener('click', (e) => {

大概應該是這樣的:

// Button which stops the countUp
document.querySelector('#stop_button').addEventListener('click', (e) => {

...考慮到您已經在前面的語句中附加了一個事件處理程序來start 'click'事件,並且沒有人會使用#start_button作為停止按鈕的id=""

暫無
暫無

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

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