繁体   English   中英

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

[英]how to persist an onclick function after page reload

我这里有一个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> 

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

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

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

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

window.localStorage.getItem('alarmTime')

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

有关更多信息,请参见本地存储上的MDN文档: https : //developer.mozilla.org/zh-CN/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 ,清除本地存储。

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

试试这个,我使用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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM