【问题标题】:Function not changing global variable globally?函数不全局更改全局变量?
【发布时间】: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 处理程序设置值之前评估文件并运行控制台日志,本质上,控制台日志在最后打印未更改的变量 usernameage,就像您声明它们一样.如果您要为用户名设置默认值,例如var username = 'bob',您将看到bob 的输出,然后它会在点击时打印您在函数中设置的任何其他内容。

标签: javascript html


【解决方案1】:
  1. 脚本在您单击按钮之前运行,此时username始终undefined

  2. 你不应该真的需要全局变量。如果这是要提交的表单,您可以在 handleClick 函数中处理它,或者让 handleClick 使用输入值调用另一个函数。

  3. 我建议您也删除内联 JavaScript,以便更好地管理它。

// Cache your elements
const usernameBox = document.querySelector('#usernameBox');
const ageBox = document.querySelector('#ageBox');
const button = document.querySelector('button');

// Add a click listener that runs the `handleClick` function
button.addEventListener('click', handleClick, false);

// Grab the values of the boxes and log them
function handleClick() {
  console.log(usernameBox.value, ageBox.value);      
}
<input id="usernameBox" placeholder="Name">
<input id="ageBox" placeholder="Age">
<br>
<button>Confirm</button>

【讨论】:

  • 好的,谢谢,就一个问题,事件监听器末尾true的目的是什么?它是如何完成这条线的?
【解决方案2】:

您的问题是&lt;script&gt; 标记在该过程的一开始就被调用。因此,您甚至在设置之前就对其进行了记录。
尝试制作一个打印出两个值的函数,例如:

function LogStuff(){
    console.log(username, age);
}

并在以下事件之后调用它:

<button onclick="changeUsername(); changeAge(); LogStuff();"id="niceButton">Confirm</button>

它在函数中起作用的原因是因为您在使用它们之前在本地设置了全局变量,所以它不再是未定义的

【讨论】:

  • 谢谢,所以如果我要添加诸如document.write(`Hello, ${username}!`) 之类的行,我是否必须将其设为函数并将其添加到要执行的onclick 操作中?
  • 向 HTML 添加一个新元素,然后像我的示例一样抓取该元素,然后是 element.textContent = `Hello, ${username}。有一些不使用document.writehere的答案。
【解决方案3】:

你已经用值调用了 console.log(username)

你可以这样做

var 用户名 = ''; 变量年龄 = '';

或者只是删除函数changeAge()下的console.log(username)

changeUsername() 和 changeAge() 只有在你点击按钮时才会执行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多