簡體   English   中英

如何使用 javascript 在刷新時保存切換按鈕 state

[英]how to save toggle button state on refresh using javascript

大家好,當我刷新頁面時,我很難保持我的切換按鈕的 state 處於打開狀態,它正確存儲在 localStorage 中,但即使經過多次嘗試,我也無法調用 function 在頁面刷新時執行

 save.addEventListener('click', () => { localStorage.setItem("checkbox1", checkBox1.checked); localStorage.setItem("checkbox2", checkBox2.checked); localStorage.setItem('timezone', timezone.selectedIndex); } function isChecked() { const checkBox1 = document.getElementById('checkbox1'); if (document.getElementById('checkbox1').checked == false) { localStorage.getItem('checkbox1'); } } window.onload = function() { isChecked(); }; }
 <form> <div class="toggle-switch-1"> <p class="notification-1">Send Email Notifications</p> <!-- toggle switch goes here --> <label type="button" class="switch-light switch-candy"> <input id="checkbox1" type="checkbox"> <span> <span id="off">Off</span> <!-- <span id="on1">On</span> --> <!-- <button onclick="check()" id="on1">On</button> --> <span id="on1">On</span> <a></a> </span> </label> </div> <div class="toggle-switch-2"> <p class="notification-2">Send Profile to Public</p> <!-- toggle switch goes here --> <label class="switch-light switch-candy" onclick=""> <input id="checkbox2" type="checkbox"> <span> <span id="off">Off</span> <span id="on2">On</span> <a></a> </span> </label> </div> <select class="form-field" id="timezone"> <option disabled selected>Select Timezone</option> <option>Eastern Standard Time (EST)</option> <option>Pacific Standard Time (PST)</option> <option>Central Standard Time (CST)</option> <option>Mountain Standard Time (MST)</option> </select> <div class="settings-button"> <button type="button" class="button-primary" id="save">Save</button> <button class="button-disabled" id="cancel">Cancel</button> </div> </form>

我試圖在刷新時保存按鈕的 state(單擊保存按鈕),但是當我刷新以及時區的下拉列表時它默認為關閉,如果有人可以幫助清除它,我將不勝感激謝謝!

您只是從本地存儲中獲取價值。 但實際上並未將其分配給任何切換按鈕。 您需要分配它們以使其工作

 function isChecked() { document.getElementById('checkbox1').checked = localStorage.getItem('checkbox1') === 'true'); }

這是它的工作原理:

  • 從本地存儲中獲取價值。

  • 保存在本地存儲中的值將是字符串類型。

  • 所以我們需要將其轉換為 Boolean 值才能使其工作。 === 檢查將為您做到這一點。

  • 最后將其分配給復選框。

暫無
暫無

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

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