警告框没有从提示打印我的用户输入变量



这里没有。我不知道为什么userInput变量没有出现在我正在创建的alertbox

<!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>```

您在这里遇到的问题是userInput的范围仅限于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>

最新更新