具有输入值的变量在函数外部赋值时为空 [英] Variable with an input’s value is empty when assigned outside a function
问题描述
我最近用 HTML 创建了一个输入框:
I recently created an input box in HTML:
<input type="number" id="aa" onchange="yy()">
<p id="xx"></p>
然后我调用了以下代码:
Then I called the following code:
var gg = document.getElementById("aa").value;
function yy(){
document.getElementById("xx").innerHTML = gg;
}
什么都没出现.
但是,如果我将脚本更改为:
However if I change the script into:
function yy(){
gg = document.getElementById("aa").value;
document.getElementById("xx").innerHTML = gg;
}
成功了!
我认为如果我首先声明变量 gg
(全局),我可以使用 yy
函数中的值.为什么第一个代码的行为不像第二个代码?
I thought that if I declared the variable gg
first (global), I could use the value in the yy
function. Why does the first code not behave like the second code?
推荐答案
那是因为您没有将值放入函数中.现在 var gg
将始终保持初始值.页面加载时为空.
Thats because you didn't put the value inside the function. Now var gg
will always hold the initial value. Which is on page load empty.
通过把它放在函数中.一旦函数被触发,该值将被检索.就您而言,您在其上放置了一个 onchange
触发器.
By putting it inside the function. The value will be retrieved as soon as the function gets triggered. In your case, you putted a onchange
trigger on it.
所以当值发生变化时,函数会在那一刻运行,并检索输入字段内的值.
So when the value changes, the function will run at that moment, and retrieves the value inside the input field.
只有提出要求才能得到东西.或者在这种情况下 JavaScript 只能在某些东西要求时才能得到东西
您在第一种情况下的函数不要求值.在你的秒情况下,JavaScript
询问元素 #aa
Your function in the first case doens't ask for a value. In your seconds case, JavaScript
asks the value
of element #aa
这篇关于具有输入值的变量在函数外部赋值时为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!