“rightbox”部分必须显示使用sessionStorage存储后在表单中输入的键和值。我尝试过Chrome、Firefox、Edge和Opera浏览器。代码在任何一个上都不起作用。
代码如下:
function doFirst() {
var button = document.getElementById('button');
button.addEventListener('click', saveStuff, false);
}
function saveStuff() {
var one = getElementById('one').value;
var two = getElementById('two').value;
sessionStorage.setItem(one, two);
display(one);
}
function display(one) {
var rightbox = document.getElementById('rightbox');
var thedata = sessionStorage.getItem(one);
rightbox.innerHTML = 'Name of variable: ' + one + '<br />Value: ' + thedata;
}
window.addEventListener('load', doFirst, false);<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<section id="leftbox">
<form>
<p>(key) One: <input type="text" id="one"></p>
<p>(value) Two: <textarea id="two"></textarea></p>
<p><input type="button" id="button" value="Save"></p>
</form>
</section>
<section id="rightbox">
Nothing yet!
</section>
</body>
</html>
发布于 2021-07-16 05:03:27
代码中的以下代码块:
function saveStuff() {
var one = getElementById('one').value;
var two = getElementById('two').value;
console.log(one, two);
sessionStorage.setItem(one, two);
display(one);
}您需要使用document.getElementById(),而不仅仅是getElementById。这会解决你的问题。
此外,您已经在第一个函数中正确使用了document.getElementById(),因此下次在发布问题之前,请确保在浏览器控制台中检查错误。从长远来看,这将对你有所帮助。
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
https://stackoverflow.com/questions/68400674
复制相似问题