2011-01-13 149 views
1

我知道这可能是最蠢的问题,但它是一个绝望的尝试从UI用户做一些事情......我从json文件中获取了一些值,然后我我将这些值传递给使用jflot绘制图形。将变量值传递给循环外

//脚本

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 dataset 
    } 
} 

是不是好,我包裹drawPlot功能之外的getJSON文件?? ..请咨询

+0

仅供参考:我删除了`jQuery`和`JSON`的标签,这个问题主要围绕基本的JavaScript用法的精神;在这种情况下,jQuery和JSON是无关紧要的。 – ken 2011-01-13 18:18:11

回答

1

没有,因为你声明wc(通过var wc)是在“每个”块的范围。

做你想做什么,你需要:

  1. 移动wc出含有两种功能

    function plot4() { 
        var wc; 
        $.getJSON("wc.json",function(data){ 
         $.each(data.posts, function(i,data){ 
          wc = data.title; 
    
  2. 或者,如果你真的想调用drawPlot从范围的each循环(你似乎没有把它全部调用!),通过wc作为参数

    // ... 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 
    } 
    
+0

感谢一堆....我用JavaScript的基础都是错误的.. :-( – Sullan 2011-01-13 18:05:15

1

参数有什么问题?

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

...或:

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 
}