You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中无需重复提示用户即可跨函数复用变量存储的信息

问题原因

你在全局作用域已经声明了firstName变量,但是在两个函数内部都用var firstName重新声明了同名局部变量,函数内的操作只会作用于局部变量,全局变量始终没有被赋值,所以双击第二个按钮时读取的未赋值局部变量就会返回undefined。

修复方案

把两个函数内部的var firstName声明删掉,直接操作全局的firstName变量即可,修改后的代码如下:

<!DOCTYPE html>
<html>
<button id="namebutton" type="submit">Click me to store your name</button>
<br>
<br>
<hr>
<br>
<button id="butt" type="submit">Double click me to return your name</button>
<script>
    var firstName;
    function firstButtonClick() {
        // 移除局部变量声明,直接给全局变量赋值
        firstName = prompt("Enter your first name", '');
        alert("Thank you for entering your name. Please click the button below!");
    }
    function secondButtonClick() {
        // 移除局部变量声明,直接读取全局变量
        alert("Your name is " + firstName);
    }
    document.getElementById("namebutton").onclick=function() {
        firstButtonClick();
    }
    document.getElementById("butt").ondblclick=function() {
        secondButtonClick();
    }
</script>
</html>

可选优化

你可以增加校验逻辑,避免用户还没输入姓名就双击第二个按钮时显示undefined:

function secondButtonClick() {
    if (firstName) {
        alert("Your name is " + firstName);
    } else {
        alert("请先点击上方按钮输入你的姓名");
    }
}

内容的提问来源于stack exchange,提问作者sb2021

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:45:02