簡體   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