簡體   English   中英

如何保持頁面重新輸入時輸入框的狀態

[英]How to keep the state of input checkbox on page reload

如何存儲Cookie以用於輸入復選框當前狀態? 每次頁面重新加載時,狀態都會恢復為默認狀態(未選中),並且我一直對此感到困惑。 我什至沒有成功使用圖書館

https://github.com/js-cookie/js-cookie Cookie.set()Cookie.get()但沒有成功。

我也一直在閱讀有關localStorage JavaScript API的信息,但似乎無法正常工作。

jQuery代碼:

$(function () {
    $('input[type="checkbox"]').click( () => {
        if ($(this).is(':checked')) {
            $('input[type="checkbox"]').prop('checked', true, localStorage.getItem('checked')).attr('checked', 'checked');
            localStorage.setItem('checked', 'checked');
            $('img').attr('src', '/full_logo_transparent.png');
            $('link#hueman-main-style-css').attr('href', '/darkstyle.min.css');
            console.log('Dark Mode enabled');
        } else {
            $('input[type="checkbox"]').prop('checked', false);
            $('link#hueman-main-style-css').attr('href', '/main.min.css');
        }
    })
});

假定記住輸入復選框的狀態並將其保存在頁面重新加載時,這樣就不必每次都切換它(它會加載其他CSS文件)

我想念什么嗎? 順序正確嗎?

該站點為https://itmagazin.info ,在右側您將找到名為“NoćniRežim”的 input:checkbox ,該input:checkbox可激活暗模式,但是單擊任何文章后,它都不會保持這種狀態。

任何幫助表示贊賞。

這比您做的要簡單得多。 只需在頁面加載時獲取最后存儲的值,並在單擊后根據復選框的狀態對其進行適當設置。

由於沙箱操作,以下代碼在Stack Overflow代碼段環境中無法使用,但您可以在此處進行測試。

 $(function () { // Reset the checkbox to the last state on the last visit // The value in localStorage will be the strings "true", "false" or // it won't be there at all, in which case "" will be returned. // The opposite of "true" (or !"true") is the Boolean false and the // opposite of that (!!"true") is the Boolean true. The opposite of // "" (!"") is the Boolean true and the opposite of that (!!"") is the // Boolean false $('#check').prop("checked", !!localStorage.getItem("darkMode")); $('#check').on("click", function() { if ($(this).is(":checked")) { localStorage.setItem('darkMode', 'true'); $('img').attr('src', '/full_logo_transparent.png'); $('link#hueman-main-style-css').attr('href', '/darkstyle.min.css'); console.log('Dark Mode enabled'); } else { localStorage.setItem('darkMode', 'false'); $('link#hueman-main-style-css').attr('href', '/main.min.css'); console.log("No Dark Mode"); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" value="test" id="check"><label for="check">Item</label> 

暫無
暫無

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

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