[英]Can't figure out why javascript isn't storing my variable
I'm trying to figure out why my javascript function isn't storing my JS variable. 我试图弄清楚为什么我的javascript函数没有存储我的JS变量。
Here's the issue. 这是问题。 I trigger my storeMacAddress function with an onclick event, and the alert shows that the 'userMac' variable gets the form value properly.
我用onclick事件触发了storeMacAddress函数,并且警报显示'userMac'变量正确获取了表单值。 I need to be able to use this value later on, so I need the value stored in a variable that my other functions can user.
稍后我需要能够使用此值,因此我需要将其存储在其他函数可以使用的变量中的值。
However, when I call my testVariable function, the console says that the 'usermac' variable is not defined. 但是,当我调用testVariable函数时,控制台会说未定义'usermac'变量。
Here's the javascript: 这是JavaScript:
function storeMacAddress()
{
var userMac = document.getElementById("MacAddress").value
alert("testing: " + userMac);
return userMac;
}
function testVariable(MacAddress)
{
alert(MacAddress);
}
Here's the html 这是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>
Since you are defining the variable inside the function, it is not visible outside the function or even to other functions, hence we can define it outside where it will be accessible to all the functions, you can just assign values inside the function or access it inside the function! 由于您是在函数内部定义变量,因此在函数外部甚至其他函数都不可见,因此我们可以在所有函数都可以访问的外部定义变量,您可以在函数内部分配值或对其进行访问里面的功能!
type attribute
of input
to text, so that the variable assignment is visible in the snippet! input
type attribute
更改为text,以便变量分配在代码段中可见! 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
. name
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.