简体   繁体   English

如何从函数内部获取变量?

[英]How to get variable from within the function?

I'm trying to access myVariable outside this function.我正在尝试在此函数之外访问myVariable Please see the code below:请看下面的代码:

var myVariable;
function drawBasic(){
...
  myVariable = document.getElementById('chart_div3');
  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));


google.visualization.events.addListener(chart, 'ready', function () {
        chart_div.innerHTML = '<img src="' + chart.getImageURI() + '">';

        myVariable.innerHTML = chart.getImageURI();
        
        myVariable = myVariable.innerHTML;

        //prints out desired value
        console.log(myVariable);


});

//prints out desired value
console.log(myVariable);
...
}
//prints out undefined
    console.log(myVariable);

I know that myVariable is defined outside the function so I was hoping it could be set inside the function and then the value could be used anywhere else, but I was wrong.我知道myVariable是在函数外部定义的,所以我希望它可以在函数内部设置,然后该值可以在其他任何地方使用,但我错了。 So my question would be how can I get the value of chart.getImageURI() and store it as a value outside the function drawBasic ?所以我的问题是如何获取chart.getImageURI()的值并将其存储为函数drawBasic之外的值?

I think this is because of a issue with your syntax in " var = myVariable ".我认为这是因为“ var = myVariable ”中的语法存在问题。 I wrote this and it works fine.我写了这个,它工作正常。

var myVariable;
drawBasic();
function drawBasic(){
   myVariable = "Test String";
   //prints out desired value
   console.log(myVariable);
}
//prints out undefined
console.log(myVariable);

jsfiddle example jsfiddle 示例

您可以将您的 chart.getImageURI() 放在 window.myVariable (始终可访问)或隐藏表单输入中,在您的函数中使用 jquery : $("#myHiddenItem").val(chart.getImageURI()) 以及您的位置需要值:$("#myHiddenItem").val()

The reason your result is undefined is probably because of the order in which your code is executed: your last console.log() is called after drawBasic() is defined , but probably before drawBasic() is executed .您的结果undefined的原因可能是因为您的代码执行顺序:您的最后一个console.log()drawBasic()定义之后调用,但可能drawBasic()执行之前调用。

Inside the function, you can do:在函数内部,您可以执行以下操作:

myVariable = chart.getImageURI();

The value of the global (and therefore readable everywhere) variable myVariable will be set when the function is called.调用函数时将设置全局(因此在任何地方都可读)变量 myVariable 的值。

After you execute drawBasic(), the value of myVariable should be correct, also when called outside the function.执行 drawBasic() 后,myVariable 的值应该是正确的,在函数外部调用时也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM