2011-10-13 67 views
0

我有一個名爲flot的圖形系統的腳本,可供下載。基本上什麼是動態改變數組VAR數據內容的最佳方式?所以我有一個用戶表,並根據用戶,我點擊它用值填充該數組,也許當第一次加載頁面時,我從表中收集所有用戶的PHP數據(可能最多20個用戶),然後onclick事件,它填充var數據變量並更改圖形。只是不知道該怎麼去做呢?或者即使我可以。爲動態jquery圖形填充變量

任何幫助將非常感謝。

<div id="placeholder" style="width:600px;height:300px"></div> 
    <p><input id="clearSelection" type="button" value="Clear selection" /> 

    <input id="setSelection" type="button" value="Select year 1994" /></p> 
    <p><label><input id="zoom" type="checkbox" />Zoom to selection.</label></p> 

<script type="text/javascript"> 
$(function() { 
var data = [ 
    { 
     label: "United States", 
     data: [[1990, 40.9], [1991, 18.7], [1992, 18.4], [1993, 19.3], [1994, 19.5], [1995, 19.3]] 
    } 
]; 

var options = { 
    series: { 
     lines: { show: true }, 
     points: { show: true } 
    }, 
    legend: { noColumns: 2 }, 
    xaxis: { tickDecimals: 0 }, 
    yaxis: { min: 0 }, 
    selection: { mode: "x" } 
}; 

var placeholder = $("#placeholder"); 

placeholder.bind("plotselected", function (event, ranges) { 
    $("#selection").text(ranges.xaxis.from.toFixed(1) + " to " + ranges.xaxis.to.toFixed(1)); 

    var zoom = $("#zoom").attr("checked"); 
    if (zoom) 
     plot = $.plot(placeholder, data, 
         $.extend(true, {}, options, { 
          xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to } 
         })); 
}); 

placeholder.bind("plotunselected", function (event) { 
    $("#selection").text(""); 
}); 

var plot = $.plot(placeholder, data, options); 

$("#clearSelection").click(function() { 
    plot.clearSelection(); 
}); 

$("#setSelection").click(function() { 
    plot.setSelection({ xaxis: { from: 1994, to: 1995 } }); 
}); 

});

回答

1

如果在頁面加載的用戶數據看起來是這樣的

var users = [ 
    { 
     name: "User1", 
     label: "United States", 
     data: [[1990, 40.9], [1991, 18.7], [1992, 18.4], [1993, 19.3]] 
    }, 
    { 
     name: "User2", 
     label: "Germany", 
     data: [[1990, 40.6], [1991, 18.2], [1992, 18.9], [1993, 19.4]] 
    }, 
    { 
     name: "User3", 
     label: "Mexico", 
     data: [[1990, 30.6], [1991, 28.2], [1992, 38.9], [1993, 29.4]] 
    } 
]; 

然後,您可以動態地寫一些內容可點擊。 。 。

for(var i = 0; i < users.length; i++) { 
    $('body').append('<div class="user">' + users[i].name + '</div>'); 

    //store the data on the element itself 
    $('.user:last').data.user_data = users[i]; 
} 

//set up the click events 
$('.user').each(function() { 
    $(this).click(function(evt) { 
     //set your data object using some of the user data 
     data = $(this).data.user_data.data; 

     //redraw the graph 
    }); 
}); 

有一點需要注意的是,您使用的數據對象需要位於可從click事件中訪問的上下文/作用域中。我縮短了數據集來證明。