页面重新加载后如何保持onclick函数

时间:2018-08-22 17:44:02

标签: javascript node.js local-storage

我这里有一个html,可根据输入时间执行简单的警报。我正在运行nodejs Web服务器,这是我的index.html

我的问题是单击“设置警报”按钮后,该功能启动,但是当然,在重新加载页面后,一切都消失了。我已经阅读了有关本地存储的信息,但是我不知道如何在这种情况下实现它。我尝试使用Garlic.js,但仅适用于文本字段和复选框之类的输入形式,而不适用于执行功能的按钮。

var alarmSound = new Audio();
alarmSound.src = 'alarm.mp3';
var alarmTimer;

function setAlarm(button) {
  var ms = document.getElementById('alarmTime').valueAsNumber;
  if (isNaN(ms)) {
    alert('Invalid Date');
    return;
  }

  var alarm = new Date(ms);
  var alarmTime = new Date(alarm.getUTCFullYear(), alarm.getUTCMonth(), alarm.getUTCDate(), alarm.getUTCHours(), alarm.getUTCMinutes(), alarm.getUTCSeconds());

  var differenceInMs = alarmTime.getTime() - (new Date()).getTime();

  if (differenceInMs < 0) {
    alert('Specified time is already passed');
    return;
  }

  alarmTimer = setTimeout(initAlarm, differenceInMs);
  button.innerText = 'Cancel Alarm';
  button.setAttribute('onclick', 'cancelAlarm(this);');
};

function cancelAlarm(button) {
  clearTimeout(alarmTimer);
  button.innerText = 'Set Alarm';
  button.setAttribute('onclick', 'setAlarm(this);')
};

function initAlarm() {
  alarmSound.play();
  document.getElementById('alarmOptions').style.display = '';
};

function stopAlarm() {
  alarmSound.pause();
  alarmSound.currentTime = 0;
  document.getElementById('alarmOptions').style.display = 'none';
  cancelAlarm(document.getElementById('alarmButton'));
};

function snooze() {
  stopAlarm();
  alarmTimer = setTimeout(initAlarm, 6000); // 5 * 60 * 100
};
<input id="alarmTime" type="datetime-local">
<button onclick="alarmButton" id="setAlarm(this);">Set Alarm</button>

<div id="alarmOptions" style="display: none;">
  <button onclick="snooze();">Snooze 5 minutes</button>
  <button onclick="stopAlarm();">Stop Alarm</button>
</div>

2 个答案:

答案 0 :(得分:2)

本地存储是跟踪会话/页面刷新之间的警报时间的好方法。

要将alarmTime保存到本地存储,请使用:

window.localStorage.setItem('alarmTime', alarmTime)

然后,当您要使用alarmTime时,请使用以下方法从本地存储中检索它:

window.localStorage.getItem('alarmTime')

要注意的一件事是,本地存储至少在流行的浏览器中只能存储字符串(请参见this post),因此请在此处记住这一点。

有关更多信息,请参见本地存储上的MDN文档:https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

要在刷新页面后再次执行功能,可以添加如下一行:

document.onload = () => setAlarm(button);

页面加载完成后,将导致setAlarm被调用。

修改

以下是如何将以上信息合并到代码中的粗略布局。我认为实际上最好将ms存储在本地存储中而不是alarmTime,以便在文档加载时可以用本地存储中的ms填充输入。

document.onload = function() {
    var ms = window.localStorage.getItem('ms');
    if (ms) {
        populateTimeInput(ms);
        var alarmButton = document.querySelector('#alarmButton');
        setAlarm(alarmButton);
    }
}

function populateTimeInput(newTime) {
    var timeInput = document.querySelector('#alarmTime');
    timeInput.value = newTime;
}

function setAlarm(button) {
    var ms = document.getElementById('alarmTime').valueAsNumber;
    if (isNaN(ms)) {
        alert('Invalid Date');
        return;
    }

    window.localStorage.setItem('ms', ms);

    // then everything else is the same
}

function cancelAlarm(button) {
    window.localStorage.clear();
    // and everything else the same
}

此代码添加了三点主要内容:

  • 页面加载完成后,此代码将检查ms的本地存储,如果找到ms的值,则会使用找到的值填充alarmTime输入,然后自动调用setAlarm
  • 调用setAlarm时,请将ms保存到本地存储中(如果ms具有有效值)。
  • 调用cancelAlarm时,清除本地存储。

这可能不是处理所有这些问题的最优雅的方法,但是我希望它至少可以使您朝正确的方向前进-不断迭代!

答案 1 :(得分:0)

尝试一下,我使用的是setInterval而不是setTimer,我将剩余时间存储在本地存储中,每0.5秒将其减少500。

var alarmSound = new Audio();
alarmSound.src = 'alarm.mp3';
var alarmTimer;

function setAlarm(button) {
  var ms = document.getElementById('alarmTime').valueAsNumber;
  if (isNaN(ms)) {
    alert('Invalid Date');
    return;
  }
  
  var alarm = new Date(ms);
  var alarmTime = new Date(alarm.getUTCFullYear(), alarm.getUTCMonth(), alarm.getUTCDate(), alarm.getUTCHours(), alarm.getUTCMinutes(), alarm.getUTCSeconds());

  var differenceInMs = alarmTime.getTime() - (new Date()).getTime();

  if (differenceInMs < 0) {
    alert('Specified time is already passed');
    return;
  }
  startTimer(differenceInMs)
  button.innerText = 'Cancel Alarm';
  button.setAttribute('onclick', 'cancelAlarm(this);');
};

function startTimer(time){
  localStorage.setItem("timeLeft",time)
  alarmTimer = setInterval(initAlarm, 500);
}

function cancelAlarm(button) {
  clearInterval(alarmTimer);
  button.innerText = 'Set Alarm';
  button.setAttribute('onclick', 'setAlarm(this);')
};

function initAlarm() {
  var timeLeft = parseInt(localStorage.getItem("timeLeft"))-500;
  if(timeLeft <= 0){
  alarmSound.play();
  document.getElementById('alarmOptions').style.display = '';
  } else {
    localStorage.setItem("timeLeft",timeLeft)
  }
};

function stopAlarm() {
  alarmSound.pause();
  alarmSound.currentTime = 0;
  document.getElementById('alarmOptions').style.display = 'none';
  cancelAlarm(document.getElementById('alarmButton'));
};

function snooze() {
  stopAlarm();
  alarmTimer = startTimer(6000); // 5 * 60 * 100
};
<input id="alarmTime" type="datetime-local">
<button onclick="alarmButton" id="setAlarm(this);">Set Alarm</button>

<div id="alarmOptions" style="display: none;">
  <button onclick="snooze();">Snooze 5 minutes</button>
  <button onclick="stopAlarm();">Stop Alarm</button>
</div>

相关问题