2011-01-13 145 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 
}