2

我想将某个复选​​框的“已选中”属性保存到本地存储中,当我刷新页面时,该属性丢失并且该复选框未选中。我可以改变什么来完成这项工作?我在这个问题上停留了一段时间。第一部分是 JS,第二部分只是我在 HTML 中定义复选框的部分。这是我的代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
 
    function myFunction() {
        var isChecked = document.getElementById("chk").checked;
        if (isChecked) {
            //header start
            document.getElementById("logo").innerHTML = "ZMP Polyhymnia";
            document.getElementById("dash").innerHTML = "Dashboard";
            document.getElementById("festival").innerHTML = "Festival";
            document.getElementById("contest").innerHTML = "Contest";
            document.getElementById("jury").innerHTML = "Jury";
            document.getElementById("res").innerHTML = "Results";
            document.getElementById("contacUs").innerHTML = "Contact";
            //header end
            //hero start
            document.getElementById("heading2").innerText = "V International Festival Polyhymnia 2020 Skopje";
            document.getElementById("firstPar").innerText = "International competition Polyhymnia: ";
            document.getElementById("secondPar").innerText = "-Concerts, Music workshops and Seminars";
            document.getElementById("thirdPar").innerText = "-Announcing Laureate of the competition and many other awards from the competition prize fond"
            document.getElementById("fourthPar").style.visibility = "hidden";
            //hero end
            //festival start
            document.getElementById("festivalH").innerHTML = "Festival";
            document.getElementById("festivalPar").innerText = "    International Festival Polyhymnia is a manifestation that is traditionally held for the third consecutive year in the second half of March through the concert halls around the capital. Participants are learners and students from the Republic of Macedonia, neighboring countries and participants from European countries. This year the festival will be held in Skopje from 28.03.2018 until 01.04.2018. This year will be represented several categories ofinstruments for solo and chamber performance (piano, flute, violin, cello, trumpet, clarinet, solo singing)."
            //festival end

        }
        else {
            //header start
            document.getElementById("logo").innerHTML = "ЗМП Полихимнија";
            document.getElementById("dash").innerHTML = "Почетна";
            document.getElementById("festival").innerHTML = "Фестивал";
            document.getElementById("contest").innerHTML = "Натпревар";
            document.getElementById("jury").innerHTML = "Жири";
            document.getElementById("res").innerHTML = "Резултати";
            document.getElementById("contacUs").innerHTML = "Контакт";
            //header end
            //hero start
            document.getElementById("heading2").innerText = "Петти меѓународен фестивал Полихимниа 2020 Скопје";
            document.getElementById("firstPar").innerText = "Во рамките на фестивалот ќе се одржи:";
            document.getElementById("secondPar").innerText = " -Меѓународен Натпревар Полихимниа 2020";
            document.getElementById("thirdPar").innerText = "-Концерт, работилници и семинари за ученици и студенти"
            document.getElementById("fourthPar").style.visibility = "visible";
            //hero end
            //festival start
            document.getElementById("festivalH").innerHTML = "Фестивал";
            document.getElementById("festivalPar").innerText = "     Меѓународниот фестивал на Полихимниа е манифестација која традиционално се одржува трета година по ред во втората половина од месец март низ концертните сали ширум главниот град. Учество земаат ученици и студенти од Република Македонија, соседните земји, но и учесници од Европските земји. Оваа година фестивалот ќе се одржи во Скопје од 28.03.2018 до 01.04.2018 година. Oваа година  ќе бидат застапени повеќе категории на инструменти за соло и камерна изведба  ( пијано, флејта, виолина,виолончело, труба, кларинет, соло пеење )."
            //festival end

        }
    }

    $('#chk').click(function (e) {
        if (e.target.checked) {
            localStorage.checked = true;
        } else {
            localStorage.checked = false;
        }
    })

    $(document).ready(function () {

        document.querySelector('#chk').checked = localStorage.checked

    });
</script>

//这是HTML部分

   <label class="switch">
     <input type="checkbox" id="chk" onclick="myFunction()">
            <span class="slider round"></span>
    </label>
4

2 回答 2

2

查看localStorage的API,你用错了。请参考这里

您应该使用localStorage.setItem()来保存数据。并使用 localStorage.getItem()` 来检索它。

所以你的代码应该是这样的:

$('#chk').click(function (e) {
    if (e.target.checked) {
        localStorage.setItem('checked','true');
    } else {
        localStorage.setItem('checked','false');
    }
})

$(document).ready(function () {

    document.querySelector('#chk').checked = (localStorage.getItem('checked') === 'true')
});
于 2020-10-05T15:20:00.333 回答
1

本地存储通过使用对象上的getItem()setItem()方法来工作localStorage。使用这些方法,您可以获取当前存储的值并设置新值。

在这里,我编写了两个抽象,这使得返回存储的检查值更容易一些。它确保返回的值是trueor false

/**
 * Get the checked state from the localStorage
 * Return the value as a boolean.
 */
function getIsChecked() {
  const storedValue = localStorage.getItem('checked');
  return Boolean(storedValue);
}

/**
 * Set the new checked state into the localStorage.
 * Only accepts a boolean value as state.
 */
function setIsChecked(state) {
  if (typeof state === 'boolean') {
    localStorage.setItem('checked', state);
  }
}

现在读出存储的值并设置您的复选框元素的选中值。

// Store the element in a constant, as it will probably never change.
const checkBoxElement = document.getElementById('chk');

// Get the current value from the localStorage.
// The result will be true or false.
const isChecked = getIsChecked();

// Set the checked value based on the localStorage value.
checkBoxElement.checked = isChecked;

更新值最好从change事件侦听器中完成,因为它会在复选框选中或取消选中时触发回调。

// Listen for change event on the checkbox element.
checkBoxElement.addEventListener('change', function(event) {
  const isChecked = event.target.checked;
  setIsChecked(isChecked);
});
于 2020-10-05T15:19:07.317 回答