localStorage getItem undefined

问题描述 投票:2回答:1

我在从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>

但它在屏幕上打印“未定义”...

javascript html html5 local-storage
1个回答
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";
};

现在它应该工作。

© www.soinside.com 2019 - 2024. All rights reserved.