我正在尝试从五个输入创建一个 Google PieChart,添加前两个数字输入并将结果存储在 sessionStorage 中。检索存储的值,并与剩余的三个输入一起创建一个 4 切片的 Google PieChart。 GoogleChart 代码可以工作,但我的问题是 sessionStorage 值不包含在饼图中,只有三个输入!这是代码:
<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"><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);
var Valoarea2 = parseInt(document.getElementById('eatvar').value);
var ValoareaFinala = Valoarea1 + Valoarea2;
sessionStorage.setItem('Adunare', ValoareaFinala);
}
google.charts.load('current', {'packages':['corechart']});
function drawChart() {
var tv = parseInt(document.getElementById('tvvar').value);
var sleep = parseInt(document.getElementById('sleepvar').value);
var other = parseInt(document.getElementById('othervar').value);
const commute = parseInt(sessionStorage.getItem('Adunare').value);
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>
从 sessionStorage 存储/检索数据一定有问题,但我无法弄清楚。任何帮助将不胜感激,谢谢。
问题在于如何从
sessionStorage
检索值。您在 .value
上使用 sessionStorage.getItem('Adunare')
,这是不正确的。
// Incorrect
const commute = parseInt(sessionStorage.getItem('Adunare').value);
// Correct
const commute = parseInt(sessionStorage.getItem('Adunare'));
用正确的行替换不正确的行,您的代码应该按预期工作。