如何将函数的结果赋值到全局变量中?

How do I assign the result of a function into a global variable?

本文关键字:全局变量 赋值 结果 函数      更新时间:2023-09-26

我不知道如何分配这个函数的结果到一个全局变量。我知道这是一个非常基本的东西,但是有人能帮忙吗?

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 -----<< */
}