我已经尝试了很多,并做了很多谷歌搜索,以使javascript中的复选框保持选中的onchange事件,但我无法做到这一点。复选框的值将存储在localStorage中,但是该复选框不会保持活动状态。请帮助我在下面尝试很多的是供您细读的代码。
下面是我的HTML代码:
<html>
<body>
<label class="switch" data-toggle="tooltip" title="click to change theme" data-placement="left">
<input type="checkbox" id="toggleme" name="toggleme" onchange="changeTheme()"> <span class="slider round"></span> </label>
<div id="changeColor">
</div>
</body>
</html>
这是我的JS代码:
<script>
function changeTheme() {
var toggleSwitch = document.getElementById('toggleme'),
toggleButton;
var divColor = document.getElementById('changeColor');
var heading = document.getElementById('sub-heading');
var td = document.getElementById('td-color');
var td_1 = document.getElementById('td-color-1');
var td_2 = document.getElementById('td-color-2');
var td_3 = document.getElementById('td-color-3');
var td_4 = document.getElementById('td-color-4');
localStorage.setItem('toggleButton', toggleSwitch.checked);
if (toggleSwitch.checked) {
var checked = JSON.parse(localStorage.getItem('toggleButton'));
document.getElementById('toggleme').checked = true;
divColor.style.backgroundColor = '#2e2e2e';
heading.style.color = '#fff';
td.style.color = '#fff';
td_1.style.color = '#fff';
td_2.style.color = '#fff';
td_3.style.color = '#fff';
td_3.style.color = '#fff';
td_4.style.color = '#fff';
} else {
localStorage.removeItem('toggleButton');
divColor.style.backgroundColor = '#fff';
heading.style.color = '#000';
td.style.color = '#2e2e2e';
td_1.style.color = '#2e2e2e';
td_2.style.color = '#2e2e2e';
td_3.style.color = '#2e2e2e';
td_4.style.color = '#2e2e2e';
}
};
window.onload = function() {
document.getElementById('toggleme').checked = localStorage.checked;
var divColor = document.getElementById('changeColor');
divColor.style.backgroundColor = '#2e2e2e';
}
</script>