开发者

Pass variable value outside out a loop

开发者 https://www.devze.com 2023-02-04 07:03 出处:网络
I know that probably would be the dumbest question to ask, but its a desperate attempt from a UI guy to do something... i have getting some values from a json file, and then i am passing those values

I know that probably would be the dumbest question to ask, but its a desperate attempt from a UI guy to do something... i have getting some values from a json file, and then i am passing those values to plot a graph using jflot.

//Script

function plot4() {
    $.getJSON("wc.json",function(data){
        $.each(data.posts, function(i,data){
            var wc = data.title;
            alert(wc);
        });
    });

    function drawPlot() {
        alert(wc);
        // function which draws plot using jFlot using a huge d开发者_StackOverflowataset
    }
}

Is it okay that i wrap the getjson file outside the drawPlot function ??.. pls advice


No, because you declare wc (via var wc) to be in the scope of the "each" block.

To do what you want, you need to either:

  1. move wc out to the scope containing both functions

    function plot4() {
        var wc;
        $.getJSON("wc.json",function(data){
            $.each(data.posts, function(i,data){
                wc = data.title;
    
  2. Or, if you actually wish to call drawPlot from your each loop (you don't seem to be calling it all!), pass wc as a parameter to it

    // ... some other code 
          var wc = data.title;
          drawPlot(wc);
    // ... some other code 
    
    function drawPlot(wc) {
        alert(wc);
       // function which draws plot using jFlot using a huge dataset
    }
    


What's wrong with parameters?

function plot4() {
    $.getJSON("wc.json",function(data){
        $.each(data.posts, function(i,data){
            var wc = data.title;
            drawPlot(wc);
        });
    });

    function drawPlot(wc) {
        // function which draws plot using jFlot using a huge dataset
    }
}

...or:

function plot4() {
    $.getJSON("wc.json",function(data){
        $.each(data.posts, function(i,data){
            var wc = data.title;
            drawPlot(wc);
        });
    });
}

function drawPlot(wc) {
    // function which draws plot using jFlot using a huge dataset
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号