我试图找出为什么我的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>
由于您在函数内部定义了变量,因此它在函数外部甚至不可见于其他函数,因此我们可以将它定义在所有函数可以访问的位置之外,您可以在函数内部分配值或访问它里面的功能!
type attribute
的input
更改为文本,以便变量赋值在代码段中可见!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>
name
。