[英]How to make a js var in a function global to use it outside?
我想使函数中的“ var id”成为全局变量。 我可以在函数外部的警报中使用它的值。 那就是我的代码:
<script> function myFunctionGetCode() { var code = getInputVal('code'); //get value from Textinputfield from html var con = "/"; var id = con+code; } alert(id); </script>
您没有指定最终目标是什么,或者为什么要尝试将id
移到全局范围,但是您可以通过将var id
(声明)简单地移到函数外部来实现,然后它将是全局的,并且所有人都可以访问职能。
显然,由于id
仅在调用myFunctionGetCode()
时获得一些值,因此alert
将显示"undefined"
。
下面的代码显示了这一点。
var id; function myFunctionGetCode() { var code = getInputVal('code'); //get value from Textinputfield from html var con = "/"; id = con+code; console.log(id) } alert(id); function getInputVal(elemId){ return document.getElementById(elemId).value; }
<input id="code"/> <button onclick="myFunctionGetCode()">Get Id</button>
但是,如果您只想在获得某个值时才使用id
值抛出警报,则应在函数内部移动alert()
。 (您仍然可以像当前一样,在函数外部或全局函数内部声明id
变量)
打开摘要以查看:
//var id; -> You can still declare it here (as global) function myFunctionGetCode() { var code = getInputVal('code'); var con = "/"; var id = con+code; //or you can declare it here, but not global alert(id); } function getInputVal(elemId){ return document.getElementById(elemId).value; }
<input id="code"/> <button onclick="myFunctionGetCode()">Get Id</button>
从示例代码中,我想您不想使全局值成为一个全局值,而是想返回一个值-毕竟,您正在函数内部进行运算,该运算根据某些输入来计算值。
因此,您将使用return关键字,并调用该函数以获取值:
<script>
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
var id = con+code;
return id;
}
alert(myFunctionGetCode());
</script>
通常,您不希望使函数变量成为全局变量,因为这意味着可以在脚本或网站的任何位置更改该值,这可能会导致副作用和函数中意外的值。 如果您需要传递使用中的功能参数(或从类似情况的文本输入中读取),则要返回结果,请使用return。
您可以在函数内部移动警报还是从函数返回“ id”值?
您可以通过执行以下操作将变量设置为全局变量:window.your_namespace.id = value;
然后以相同的方式访问变量:value = window.your_namespace.id
但最好不要使用全局名称空间传递数据。
您必须将var id设置为window对象的属性,然后才能在函数外部访问id。
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
window.id = 10;// Change to this
}
myFunctionGetCode();
alert(id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.