在 HTML 表单中,我想在单击按钮时显示用户输入。这是通过调用 JavaScript 函数来完成的。用户输入保存在一个变量中,然后在函数内使用该变量。问题是,函数无法识别 var,除非它是在其中定义的。
以下是HTML和JS代码。查看 ( https://dl.dropboxusercontent.com/u/4301151/stackoverflow/varNoDefined.html )
<p><label>Name:</label>
<input type="text" name="userName" id="userName" placeholder="e.g John Lewis"/>
</p>
<input type="submit" name="submitButton" value="Display" onclick="run()"/>
<p>Name Provided: <label id="outputUserName"></label></p>
var userName = document.getElementById("userName").value;
function run() {document.getElementById("outputUserName").innerHTML = userName;}
如果函数内包含以下内容,它将正常工作:
document.getElementById("outputUserName").innerHTML = document.getElementById("userName").value;
或者如果我在函数内定义 var
我需要 var 是全局的,以便将它与其他函数一起使用,而不是多次定义它
最佳答案
The problem, the function doesn't recognize the var unless it's defined inside it.
不,这不是问题。该变量已被识别,但它没有您想要的值。
您正在尝试在用户键入任何内容之前读取输入的值。 userName
将仅保存一个空字符串。您可以通过为输入提供默认值来轻松验证这一点:
<input type="text" name="userName" id="userName" value="default value"/>
您必须在需要/想要时读取该值。作为妥协,您可以保留对 DOM 元素的引用作为全局变量:
var userName = document.getElementById("userName");
function run() {
document.getElementById("outputUserName").innerHTML = userName.value;
}
同样相关:Why does jQuery or a DOM method such as getElementById not find the element?
关于javascript - 在 onClick 中调用时,JavaScript 函数内未定义全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26558155/