You need to enable JavaScript to run this app. JavaScript 基于localStorage实现多表单输入跨页传值展示
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript 基于localStorage实现多表单输入跨页传值展示

问题根因

当前代码跳转后仅能展示物种输入值,核心原因:

  • 表单提交时的存储逻辑,仅把species输入框的值写入了localStorage,完全没有读取、存储最低温度输入框的内容
  • 目标页的渲染逻辑仅读取单个存储值,直接覆盖了整个展示节点的内容,既没有预留温度值的展示位置,也没有对应的取值逻辑
调整后代码

form.html 代码

将提交函数中的存储逻辑修改为同时读取两个输入框的值,采用规范的setItem方法写入localStorage,避免属性名冲突:

<form id="form" method="GET" action="customanimal.html">
    Species: <input type="text" name="species" id="species">
    Temperature(low): <input type="text" name="templow" id="templow">
    <input type="button" value="Submit" onclick="submitForm()">
</form>
<script>
function submitForm(){
    if(typeof(localStorage) != "undefined"){
        // 分别存储两个输入项的内容,去除输入前后的无效空格
        localStorage.setItem("species", document.getElementById("species").value.trim());
        localStorage.setItem("templow", document.getElementById("templow").value.trim());
    }
    document.getElementById("form").submit();
}
</script>

customanimal.html 代码

将展示逻辑调整为分别读取两个存储值,按格式拼接展示内容,增加空值兜底,避免未填写时出现undefined的无意义内容:

<body onload="setData()">
    <p id="show"></p>
    <script>
    function setData(){
        if(typeof(localStorage) != "undefined"){
            const inputSpecies = localStorage.getItem("species") || "未填写";
            const inputTemplow = localStorage.getItem("templow") || "未填写";
            document.getElementById("show").innerHTML = `
                物种:${inputSpecies} <br>
                最低温度:${inputTemplow}
            `;
        }
    }
    </script>   
</body>

内容的提问来源于stack exchange,提问作者Ma'alin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.15 21:24:03