【问题标题】:alert box not printing my user input variable from promp [duplicate]警告框未从提示符打印我的用户输入变量 [重复]
【发布时间】:2021-02-25 13:45:34
【问题描述】:

这里是菜鸟。我不知道为什么我正在创建的警报框中没有出现 userInput 变量

<!DOCTYPE HTML>
<html>
    <head>
        <title>fns</title>
    </head>
    <body>
        <button onclick="namebox()">Enter Name</button>
        <button onclick="yoyoyo()">Generate Greeting!</button>

    </body>
    <script>
    function namebox() {
        var userInput = prompt("Enter your name");
    }
    function yoyoyo() {
        alert("Hello" + userInput);
    }
    </script>
</html>```

【问题讨论】:

  • userInputnamebox 的本地,在这两个函数之外定义它。
  • 阅读有关variable scope 的信息。或者打开前3章的任何教程,都会有一样的。

标签: javascript html css alert prompt


【解决方案1】:

您在这里遇到的问题是userInputscope 仅限于namebox 函数。您必须提高范围,以便在两个函数中都可以访问它。

<html>
<head>
<title>fns</title>
</head>
<body>
<button onclick="namebox()">Enter Name</button>
<button onclick="yoyoyo()">Generate Greeting!</button>

</body>
<script>
var userInput; // declared outside both functions, so scope is available in both
function namebox() {
    userInput = prompt("Enter your name");
}
function yoyoyo() {
    alert("Hello" + userInput);
}
</script>
</html>

【讨论】:

    猜你喜欢
    • 2022-07-05
    • 2016-10-20
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    相关资源
    最近更新 更多