如何将函数的结果赋值到全局变量中?
How do I assign the result of a function into a global variable?
我不知道如何分配这个函数的结果到一个全局变量。我知道这是一个非常基本的东西,但是有人能帮忙吗?
var pixel_code = null
function captureValue(){
pixel_code = document.getElementById("baseText").value;
return pixel_code;
}
pixel_code = captureValue();
感谢您分享您的尝试。我明白你的担忧。captureValue()函数是异步运行的,因此console.log()
在定义它之后不久还没有值。我对jsfiddle进行了剥离和刺激,得出了这个工作示例:
<html>
<head>
</head>
<body>
<h1>Welcome to the AdRoll SandBox</h1>
<textarea id="baseText" style="width:400px;height:200px"></textarea><br />
<input type="button" value="test" id="text_box_button" onclick="captureValue()"/>
<input type="button" value="get" id="text_box_button2" onclick="getValue()"/>
<script>
var pixel_code = null;
function captureValue(){
pixel_code = document.getElementById("baseText").value;
return false;
}
function getValue() {
alert(pixel_code);
return false;
}
</script>
</body>
</html>
我添加了第二个按钮。在文本框中输入,按"test"(设置值),再按"get"获取全局变量的值。
下面是使用jQuery和闭包避免全局变量的相同示例:
<html>
<head>
</head>
<body>
<h1>Welcome to the AdRoll SandBox</h1>
<textarea id="baseText" style="width:400px;height:200px"></textarea><br />
<input type="button" value="test" id="text_box_button" />
<input type="button" value="get" id="text_box_button2" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
var pixel_code = null;
$("#text_box_button").click(function (){
pixel_code = document.getElementById("baseText").value;
return false;
});
$("#text_box_button2").click(function () {
alert(pixel_code);
return false;
});
});
</script>
</body>
</html>
如果页面重新加载,你的变量将被重置为初始状态
您在函数内外重用了pixel_code,这不是一个很好的模式,但是您所显示的代码应该能按预期工作。你看到了什么错误?在这个代码周围有什么代码没有显示?所有这些都可以嵌套在另一个函数中吗?(感谢@JosephSilver的认可)
请尝试一下,
var pixel_code='';
function captureValue(){
return document.getElementById("baseText").value;
}
function getValueBack()
{
pixel_code = captureValue();
//alert(pixel_code); /* <----- uncomment to test -----<< */
}
相关文章:
- Javascript变量赋值|
- 如何在javascript中为全局变量赋值
- 我可以在javascript中的回调函数中为变量赋值吗
- 无法在函数中检索全局变量的值
- JavaScript 变量赋值的行为令人惊讶
- 为什么 Javascript 在变量赋值时将 null 转换为字符串
- JavaScript: 变量赋值 in for 语句 |在前面或里面
- 我可以将变量赋值为数组值吗?
- 变量赋值无效
- 一行中的多个变量赋值
- jQuery- 为什么为全局变量赋值在函数中不起作用
- 通过输入法为全局变量赋值
- 如何为全局变量赋值,并在jquery/javascript中的其他函数中使用它
- 给回调函数中的全局变量赋值并返回它[Node.js]
- 使用$给全局变量赋值.Ajax (JQuery)
- Jquery全局变量赋值和在javascript函数中的使用
- 将变量赋值给全局作用域有什么危险或好处吗?
- 如何在一个函数中声明一个全局变量赋值,并在另一个函数中使用
- 在 ajax 调用中为全局变量赋值,并在单独的.js文件中使用它
- 给剑道网格列模板中的全局变量赋动态值