我在从localStorage检索值时遇到了一些麻烦。我试图存储输入和从表单中选择内容,然后单击提交后在另一页上使用它。表单如下所示:
<form action="thank-you.html" role="form" id="form" data-toggle="validator" method="get" onsubmit="callme()">
<div class="form-group col-md-6">
<label for="inputSurfaceDuTerrain">Surface du terrain (Optionnel)</label>
<div class="input-group">
<input type="number" class="form-control" id="inputSurfaceDuTerrain" name="inputSurfaceDuTerrain"
placeholder="Ex. 500" />
<div class="input-group-append">
<div class="input-group-text">m²</div>
</div>
</div>
</div>
</form>
还有该文件的JS:
function callme() {
let inputSurfaceDuTerrain = document.getElementById('inputSurfaceDuTerrain');
localStorage.setItem('inputSurfaceDuTerrain', inputSurfaceDuTerrain.value);
};
在我的另一个文件“ thank-you.html”页面上,我想在屏幕上打印输入值。这是我的html和JS:
<p id="inputSurfaceDuTerrain"></p>
<script>
window.onload = function () {
document.getElementById('inputSurfaceDuTerrain').innerText = "inputSurfaceDuTerrain, " + localStorage.getItem('inputSurfaceDuTerrain');
};
</script>
但是它在屏幕上显示“未定义” ...
答案 0 :(得分:3)
您正在提交的表单会转到新页面-因此,您必须手动设置URL。
将表单更改为此:
<form role="form" id="form" data-toggle="validator">
并将此JavaScript添加到其所在的页面上:
document.getElementById("form").addEventListener("submit", callme);
function callme(event) {
event.preventDefault();
let inputSurfaceDuTerrain = document.getElementById('inputSurfaceDuTerrain');
localStorage.setItem('inputSurfaceDuTerrain', inputSurfaceDuTerrain.value);
window.location.href = "thank-you.html";
};
现在应该可以了。