【发布时间】:2021-06-23 00:16:56
【问题描述】:
由于某种原因,我的函数中设置的变量仅适用于函数的范围,即使声明前面有窗口:
<body>
<input id="usernameBox" placeholder="Name">
<input id="ageBox" placeholder="Age">
<br>
<button onclick="changeUsername(), changeAge()"id="niceButton">Confirm</button>
<script>
var username;
var age;
function changeUsername(){
window.username=document.getElementById("usernameBox").value
console.log(username)
}
function changeAge(){
window.age=document.getElementById("ageBox").value
console.log(age)
}
console.log(username);
</script>
最终的控制台日志应该记录在文本框“usernameBox”中插入的内容,但它只是打印未定义,即使在单击按钮之后也是如此。我什至在函数中添加了一个检查器,它们在单击时正确记录文本框内的内容,那么为什么用户名在函数之外仍未定义?
【问题讨论】:
-
您在文档顶部声明了 2 个变量,没有任何赋值(它们在控制台日志时未定义)。当页面加载时,在您使用 onclick 处理程序设置值之前评估文件并运行控制台日志,本质上,控制台日志在最后打印未更改的变量
username和age,就像您声明它们一样.如果您要为用户名设置默认值,例如var username = 'bob',您将看到bob的输出,然后它会在点击时打印您在函数中设置的任何其他内容。
标签: javascript html