我试图找出为什么我的 javascript 函数没有存储我的 JS 变量。
问题来了。我使用 onclick 事件触发 storeMacAddress 函数,并且警报显示“userMac”变量正确获取了表单值。我需要稍后能够使用该值,因此我需要将该值存储在其他函数可以使用的变量中。
但是,当我调用 testVariable 函数时,控制台显示“usermac”变量未定义。
这是 JavaScript:
function storeMacAddress()
{
var userMac = document.getElementById("MacAddress").value
alert("testing: " + userMac);
return userMac;
}
function testVariable(MacAddress)
{
alert(MacAddress);
}
这是 html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src='./index.js'>
</script>
</head>
<body>
<h1></h1>
<p></p>
<div>
<form id="userRequest">
Mac Address: <input type="text" id="MacAddress"><br>
<input type="submit"
onclick="storeMacAddress();"
value="Save Mac Address">
</form>
</div>
<button onclick="
testVariable(userMac);
">Test</button>
</body>
</html>
最佳答案
由于您在函数内部定义变量,因此它在函数外部甚至对其他函数都是不可见的,因此我们可以在所有函数都可以访问它的外部定义它,您只需在函数内部赋值即可或者在函数内部访问它!
- 注意:我已将
input
的type 属性
更改为文本,以便 变量赋值在代码片段中可见!
var userMac;
function storeMacAddress() {
userMac = document.getElementById("MacAddress").value
if (userMac)
alert("testing: " + userMac);
return userMac;
}
function testVariable(MacAddress) {
if (MacAddress)
alert(MacAddress);
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src='./index.js'>
</script>
</head>
<body>
<h1></h1>
<p></p>
<div>
<form id="userRequest">
Mac Address: <input type="text" id="MacAddress"><br>
<input type="button" onclick="storeMacAddress();" value="Save Mac Address">
</form>
</div>
<button onclick="
testVariable(userMac);
">Test</button>
</body>
</html>
关于javascript - 无法弄清楚为什么 javascript 不存储我的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47857383/