Google PieChart无法从sessionStorage取值的技术问题求助
问题分析与解决方案
核心错误:sessionStorage读取方式错误
你代码里读取sessionStorage的写法有误:
const commute = parseInt(sessionStorage.getItem('Adunare').value);
sessionStorage.getItem('Adunare')直接返回存储的字符串数值,不存在.value属性,这会导致commute被解析成NaN,而Google Charts会自动忽略值为NaN的饼图条目,所以你看不到"Commute"分片。
正确写法应该是:
const commute = parseInt(sessionStorage.getItem('Adunare')) || 0;
加|| 0是为了处理存储值不存在(比如还没输入数值就提交)的情况,避免出现NaN。
次要问题:计算逻辑触发不完整
当前calculeaza()函数只在eatvar输入框的onkeyup事件触发,当你修改workvar的值时,不会重新计算总和并存入sessionStorage,导致存储的数值不是最新的。需要给workvar也加上onkeyup="calculeaza();"事件。
修正后的完整代码
<body> <p>How many hours do you spend per week?</p> <form id="form1" onsubmit="drawChart(); return false" > <label for="workvar">Working: </label><input type="text" id="workvar" autocomplete="off" onkeyup="calculeaza();"><br> <label for="eatvar">Eating: </label><input type="text" id="eatvar" autocomplete="off" onkeyup="calculeaza();"><br> <label for="tvvar">Watching tv: </label><input type="text" value="35" id="tvvar"><br> <label for="sleepvar">Sleeping: </label><input type="text" value="21" id="sleepvar"><br> <label for="othervar">Other: </label><input type="text" value="17" id="othervar"><br> <button type="submit" value="Submit">Submit</button> </form> <div id="piechart" class="chart"></div> </body> <script> function calculeaza() { var Valoarea1 = parseInt(document.getElementById('workvar').value) || 0; var Valoarea2 = parseInt(document.getElementById('eatvar').value) || 0; var ValoareaFinala = Valoarea1 + Valoarea2; sessionStorage.setItem('Adunare', ValoareaFinala); } google.charts.load('current', {'packages':['corechart']}); function drawChart() { var tv = parseInt(document.getElementById('tvvar').value) || 0; var sleep = parseInt(document.getElementById('sleepvar').value) || 0; var other = parseInt(document.getElementById('othervar').value) || 0; const commute = parseInt(sessionStorage.getItem('Adunare')) || 0; var data = google.visualization.arrayToDataTable([ ['Task', 'Hours per Week'], ['Commute', commute], ['Watch TV', tv], ['Sleep', sleep], ['Other', other] ]); var options = { title: 'Weekly Activities' }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } window.onresize = function() { drawChart(); } </script>
额外在calculeaza()里给parseInt加了||0,避免输入非数字时出现NaN导致总和异常。
内容的提问来源于stack exchange,提问作者Felix
相关产品推荐
相关产品推荐

