为动态Jquery Graph填充变量

时间:2011-10-13 23:17:54

标签: javascript jquery

我有一个名为flot的图形系统,可以下载。基本上什么是动态更改数组VAR数据内容的最佳方法?所以我有一个用户表,根据用户点击它,用数据填充该数组,也许当页面首次加载时我从php收集表中所有用户的数据(最多可能是20个用户)然后是onclick事件,填充var数据变量并更改图形。只是不确定如何去做?或者即使我可以。

任何帮助都会非常感谢。

  <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 个答案:

答案 0 :(得分: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事件中访问的上下文/范围中。我缩短了数据集以进行演示。