[英]How to pass a variable into another function to be called - Javascript
I am trying to get this to work: 我想让这个工作:
<!DOCTYPE html>
<html>
<body>
<form><input type='button' id='confirm' value="Confirm"/></form>
<p id="getvariable"></p>
<script>
function a(){var t= 5;}
function b(){return t;}
document.getElementById('confirm').onclick = function(){
document.getElementById("getvariable").innerHTML = b();}
</script>
</body>
but I can't pass a variable to the other function. 但我无法将变量传递给另一个函数。 Any help would be great!
任何帮助都会很棒!
The problem is that the variable t is in the scope of the function a when you set it. 问题是变量t在设置时属于函数a的范围。 It needs to be global.
它需要是全球性的。 Like this:
像这样:
var t = 0;
function a(){ t = 5;}
function b(){return t;}
document.getElementById('confirm').onclick = function(){
document.getElementById("getvariable").innerHTML = b();
}
You can't use a value in another function that has been defined locally in a particular function. 您不能在已在特定函数中本地定义的另一个函数中使用值。
So this is wrong: 所以这是错的:
function a(){var t= 5;}
function b(){return t;}
What I would do is : 我会做的是:
var t=0;
function a(){t= 5;}
function b(){return t;}
document.getElementById('confirm').onclick = function(){
document.getElementById("getvariable").innerHTML = b();}
Here's a link that can help you : http://www.w3schools.com/js/js_scope.asp 这是一个可以帮助您的链接: http : //www.w3schools.com/js/js_scope.asp
t valriable should be decalred outside the function scope t valriable应该在功能范围之外进行decalred
var t = 0;
function a(){
t = 5;
}
function b(){
return t;
}
document.getElementById('confirm').onclick = function(){
document.getElementById("getvariable").innerHTML = b();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.