页面加载时如何根据布尔值隐藏周日时段表单?
问题分析与修复方案
你遇到的问题核心在于元素选择错误、布尔值判断逻辑偏差,以及缺少状态持久化机制——这是实现“下次返回页面保持表单隐藏”的关键。下面逐一拆解并给出修复方案:
错误点拆解
- 元素选择错误:
getElementById()仅支持传入元素ID字符串,不能使用CSS属性选择器'input[name="sunday_bool"][type="checkbox"]',需改用document.querySelector()。 - 布尔值判断逻辑错误:
sunTrueBool是DOM元素对象,不是布尔值,你需要读取它的.checked属性来判断是否勾选。 - 缺失状态持久化:当前代码仅读取页面加载时的即时状态,未将用户选择的状态保存到本地或后端,导致刷新页面后状态丢失。
修复后的完整代码
JavaScript部分(add_timeslot.js)
const sunForm = document.getElementsByClassName('sun_time_slot_form'); const mainForm = document.querySelector('#all-add-form'); const addSunBtn = document.querySelector("#add-sun-form"); const submitFormBtn = document.querySelector('[type="submit"]'); const totalForms = document.querySelector("[id$='-TOTAL_FORMS']"); const sunDeleteBtn = document.querySelector(".sun_time_slot_form"); let formCount = sunForm.length - 1; addSunBtn.addEventListener('click', function (e) { e.preventDefault(); const newSunForm = sunForm[0].cloneNode(true); const formRegex = RegExp(`id_sunday_formset-(\\d){1}-`, 'g'); formCount++; newSunForm.innerHTML = newSunForm.innerHTML.replace(formRegex, `id_sunday_formset-${formCount}-`); mainForm.insertBefore(newSunForm, submitFormBtn); totalForms.setAttribute('value', `${formCount + 1}`); }); function updateSunForm() { let count = 0; for (let sun_form of sunForm) { const sunFormRegex = RegExp(`TOTAL_FORMS-(\\d){1}-`, 'g'); sun_form.innerHTML = sun_form.innerHTML.replace(sunFormRegex, `TOTAL_FORMS-${count++}-`) } } mainForm.addEventListener('click', (e) => { if (e.target.classList.contains('delete-sun-form')) { e.preventDefault(); e.target.parentElement.querySelector('input[name$="-DELETE"][type="checkbox"]').checked = true; e.target.parentElement.style.display = "none"; } }); function sunCheckOne() { const x = document.querySelectorAll('input[name$="sunday_bool"][type="checkbox"]'); for (let i = 0; i < x.length; i++) { x[i].checked = !x[i].checked; // 同步保存状态到本地存储 localStorage.setItem('sunday_available', !x[i].checked); } } const btn = document.querySelector('#sun-not-available'); btn.addEventListener('click', updateBtn); function updateBtn() { if (btn.value === 'Not Available Sunday') { btn.value = "I'm Available Sunday"; } else { btn.value = 'Not Available Sunday'; } } function sunHideShow() { const S = document.getElementById("sun-hide-id"); const isAvailable = localStorage.getItem('sunday_available') === 'false'; S.style.display = isAvailable ? "block" : "none"; // 同步勾选状态 const sunBoolInput = document.querySelector('input[name="sunday_bool"][type="checkbox"]'); if (sunBoolInput) { sunBoolInput.checked = !isAvailable; } } // 页面DOM加载完成后初始化状态 document.addEventListener('DOMContentLoaded', function boolNotAvailable() { const sunHide = document.getElementById("sun-hide-id"); const sunTrueBool = document.querySelector('input[name="sunday_bool"][type="checkbox"]'); // 优先读取本地存储的状态,无存储则用默认勾选状态 const savedState = localStorage.getItem('sunday_available'); const shouldHide = savedState ? savedState === 'true' : sunTrueBool?.checked; if (shouldHide) { sunHide.style.display = "none"; btn.value = "I'm Available Sunday"; } else { sunHide.style.display = "block"; btn.value = 'Not Available Sunday'; } }); // 表单提交时同步保存状态 mainForm.addEventListener('submit', function() { const sunTrueBool = document.querySelector('input[name="sunday_bool"][type="checkbox"]'); localStorage.setItem('sunday_available', sunTrueBool.checked); });
Django模板部分
{% load crispy_forms_tags %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" type="text/css" href="{% static 'css/availability_update_new.css' %}"> </head> <body> <input type="button" class="sun-not-available" value="Not Available Sunday" onclick="sunCheckOne(); sunHideShow()" id="sun-not-available"> <form id="all-add-form" method="POST" action="" enctype="multipart/form-data"> <div class="sun-hide" id="sun-hide-id"> <div class="sunday-all" id="sunday-all-id"> {% csrf_token %} <legend class="bottom mb-4">Profiles Info</legend> <div class="sun-bool"> {{ sun_bool.sunday_bool }} </div> </div> {{ sunday_formset.management_form }} {% for sun_form in sunday_formset %} {% for hidden in sun_form.hidden_fields %} {{ hidden }} {% endfor %} <div class="sun_time_slot_form"> {{ sun_form }} <button class="delete-sun-form" type="button" id="delete-sun-btn"> Delete This Sunday Timeslot</button> </div> {% endfor %} <button id="add-sun-form" type="button" class="button">Add Other Sunday Times</button> </div> <input type="submit" name="submit" value="Submit" class="btn btn-primary"/> </form> <script type="text/javascript" src="{% static 'js/add_timeslot.js' %}"></script> </body> </html> {% endblock content %}
关键修复说明
- 修正元素选择:替换
getElementById为querySelector,正确获取目标复选框元素。 - 修正布尔判断逻辑:读取DOM元素的
.checked属性,而非直接判断元素对象本身。 - 添加本地存储持久化:用
localStorage保存用户选择的周日可用性状态,确保页面刷新或重新打开时状态一致。 - 改用可靠的加载事件:用
DOMContentLoaded替代document.onload,在DOM结构加载完成后立即执行初始化逻辑,避免元素未加载导致的错误。
内容的提问来源于stack exchange,提问作者Wideback
相关产品推荐
相关产品推荐

