多JS文件变量共享问题:勾选复选框无法更新跨页面仪表盘
跨页面同步复选框状态与仪表盘数值解决方案
核心问题是两个独立HTML页面属于不同浏览器执行上下文,import/require仅能在同一执行环境内共享模块,无法直接跨页面传递变量。你已使用localStorage存储复选框状态,只需在第二个页面读取该状态并据此更新仪表盘数值即可。
第一步:优化第一个页面代码(消除冗余)
第一个HTML文件(修正后)
<!DOCTYPE html> <head> <title>Energenius</title> <link rel="stylesheet" href="Static/living.css"> <script src="Static/living.js"></script> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div class="dashboard"> <header> <div class="f fe"> <div class="icon icon-w"></div> <div class="heading"> <nav> <label for="touch"><span class="account">parter</span></label> <input type="checkbox" id="touch"> <ul class="slide"> <li><a href="/E1L">Apartament 1</a></li> <li><a href="/E2L">Apartament 2</a></li> </ul> </nav> <h2 class="title">Cloudy</h2> </div> </div> <div class="weather f"> <div> <strong id="volt">Consumption Analytics</strong> <p style="color: white;"><button id="analytics" onclick="redirect()">🗠</button></p> </div> </div> </header> <section> <div class="category"> <ul> <li><a href="#!" class="active">Living Room</a></li> </ul> </div> <form> <div class="appliances"> <div class="appliance"> <input type="checkbox" name="a" id="a"> <label for="a"> <i class="l"></i> <strong>Lamp</strong> <span data-o="opened" data-c="closed"></span> <small></small> </label> </div> </div> </form> </section> </div> </body> </html>
第一个页面的JS代码(修正后)
// 处理复选框状态变更 function handleChange1() { const checkbox = document.getElementById("a"); const isChecked = checkbox.checked; // 存储状态到localStorage localStorage.setItem("aChecked", isChecked.toString()); // 修改URL(可选,按需保留) history.pushState(null, null, isChecked ? "/P" : "/p"); } // 页面加载时恢复复选框状态 window.addEventListener('load', function() { const savedState = localStorage.getItem("aChecked"); if (savedState === "true") { document.getElementById("a").checked = true; } }); // 绑定复选框变更事件 document.getElementById("a").addEventListener("change", handleChange1); // 跳转至分析页面 function redirect() { location.href = "analytics"; }
优化点:
- 移除冗余的
onchange属性和location.reload(),避免不必要的页面刷新 - 直接用
checkbox.checked设置状态,符合DOM规范 - 简化
redirect函数逻辑
第二步:修改第二个页面,读取localStorage状态更新仪表盘
第二个页面的JS代码(修改后)
$(document).ready(function() { const $delay = 1000, totalPoints = 25, $voltageDisplay = $('div.volts'), $currentDisplay = $('div.amps'), $moistureDisplay = $('div.moisture'); // 根据复选框状态获取对应数值 function getValuesBasedOnCheckbox() { const isLampOn = localStorage.getItem("aChecked") === "true"; // 可自定义开/关状态下的数值,示例用固定值,也可结合getRandomInt函数 return isLampOn ? [12.5, 2.3, 4.7] : [0, 0, 0]; } function updateVoltage(value) { $voltageDisplay.html(value.toFixed(1)); } function updateCurrent(value) { $currentDisplay.html(value.toFixed(1)); } function updateMoisture(value) { $moistureDisplay.html(value.toFixed(1) + '<span>RON</span>'); } function updateSensorDisplayValues(d) { updateVoltage(d[0]); updateCurrent(d[1]); updateMoisture(d[2]); } // 初始化图表配置 Highcharts.setOptions({ global: { useUTC: false }, plotOptions: { series: { marker: { enabled: false } } }, tooltip: { enabled: false } }); const chart = $('#sensorData').highcharts({ chart: { type: 'spline', events: { load: function() { const voltage = this.series[0]; const current = this.series[1]; const moisture = this.series[2]; setInterval(function() { const x = (new Date()).getTime(); // 获取当前复选框状态对应的数值 const [volts, amps, mPercent] = getValuesBasedOnCheckbox(); voltage.addPoint([x, volts], false, true); current.addPoint([x, amps], false, true); moisture.addPoint([x, mPercent], true, true); updateSensorDisplayValues([volts, amps, mPercent]); }, $delay); } } }, title: { text: 'Sensor Data' }, xAxis: { type: 'datetime', tickPixelInterval: 500 }, yAxis: [{ title: { text: 'VOLTAGE', style: { color: '#2b908f', font: '13px sans-serif' } }, min: 0, max: 15, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, { title: { text: 'CURRENT', style: { color: '#90ee7e', font: '13px sans-serif' } }, min: 0, max: 4, opposite: true, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, { title: { text: 'COST ⠀TOTAL', style: { color: '#f45b5b', font: '13px sans-serif' } }, min: 0, max: 100, opposite: true, plotLines: [{ value: 0, width: 1, color: '#808080' }] }], tooltip: { formatter: function() { const unitOfMeasurement = this.series.name === 'VOLTAGE' ? ' V' : ' A'; return '<b>' + this.series.name + '</b><br/>' + Highcharts.numberFormat(this.y, 1) + unitOfMeasurement; } }, legend: { enabled: true }, exporting: { enabled: false }, series: [{ name: 'VOLTAGE', yAxis: 0, style: { color: '#2b908f' }, data: (function() { const data = []; const time = (new Date()).getTime(); const initialValues = getValuesBasedOnCheckbox(); for (let i = -totalPoints; i <= 0; i += 1) { data.push({ x: time + i * $delay, y: initialValues[0] }); } return data; }()) }, { name: 'CURRENT', yAxis: 1, data: (function() { const data = []; const time = (new Date()).getTime(); const initialValues = getValuesBasedOnCheckbox(); for (let i = -totalPoints; i <= 0; i += 1) { data.push({ x: time + i * $delay, y: initialValues[1] }); } return data; }()) }, { name: 'Cost Total', yAxis: 2, data: (function() { const data = []; const time = (new Date()).getTime(); const initialValues = getValuesBasedOnCheckbox(); for (let i = -totalPoints; i <= 0; i += 1) { data.push({ x: time + i * $delay, y: initialValues[2] }); } return data; }()) }] }).highcharts(); // 监听localStorage变化,两个页面同时打开时实时同步 window.addEventListener('storage', function(e) { if (e.key === 'aChecked') { const [volts, amps, mPercent] = getValuesBasedOnCheckbox(); updateSensorDisplayValues([volts, amps, mPercent]); // 更新图表数据(可选) const x = (new Date()).getTime(); chart.series[0].addPoint([x, volts], false, true); chart.series[1].addPoint([x, amps], false, true); chart.series[2].addPoint([x, mPercent], true, true); } }); });
修改点:
- 添加
getValuesBasedOnCheckbox函数,读取localStorage状态返回对应数值 - 初始化图表时用当前状态数值填充初始数据
- 定时器中实时获取最新状态数值,更新仪表盘和图表
- 添加
storage事件监听,实现多页面实时同步
关键原理
- localStorage跨页面共享:同一域名下所有页面可读写
localStorage数据 - storage事件监听:其他页面修改
localStorage时,当前页面触发事件实现实时同步 - 避免页面刷新:通过
localStorage同步状态,无需刷新页面
内容的提问来源于stack exchange,提问作者qMicu
相关产品推荐
相关产品推荐

