从DIV元素中的数据更新amChart图上的数据

时间:2014-06-06 14:20:07

标签: javascript html amcharts

我的JavaScript和amCharts图表存在一些问题。

我想要实现的是使用来自DIV元素的新数据重新加载amChart线图。在我的最后一页中,这个DIV元素将被动态更新和隐藏,以便最终用户不会看到。需要重新绘制图表而不重新加载页面。

我有一个JSFiddle页面,其中包含我尝试重新加载数据的示例。

http://jsfiddle.net/gnuoynomis/Se2UE/1/

我试过:

  • 创建点的对象并将它们添加到一个字符串中,创建一个对象字符串,但这似乎不会加载到图形中。

    function LoadNewDataFromDIV_V1()
    {
      //This function attempts to use a string of objects to pass to the dataprovider setting
      var ChartData = document.getElementById("NewData").innerHTML;
      var CD = ChartData.split("},{");    //Split the string on the different day elements
    
      var NewChartData = "";
      for(i=0; i<CD.length; i++)
      {
        var D = CD[i];
        D = D.replace("{","");    //Remove any additional { that may exist to help with the formating later
        D = D.replace("}","");    //Remove any additional } that may exist to help with the formating later
        D = "{" + D + "}";        //Add a { and } to reformat the line correctly from the splitting
    
        if(NewChartData != "")
          NewChartData += ",";
        NewChartData += JSON.parse(D);    //Add the parsed object to the data string
      }
    
      chart.dataProvider = NewChartData;    //Update graph data
      chart.validateData();    //Revalidate chart data
    }
    
  • 我也尝试将对象添加到数组中并尝试传递但仍然没有运气。

    function LoadNewDataFromDIV_V2()
    {
      //This function attempts to use an array to store the data and pass this to the dataprovider setting
      var ChartData = document.getElementById("NewData").innerHTML;
      var CD = ChartData.split("},{");    //Split the string on the different day elements
    
      var NewChartDataArray = [];
      for(i=0; i<CD.length; i++)
      {
        var D = CD[i];
        D = D.replace("{","");    //Remove any additional { that may exist to help with the formating later
        D = D.replace("}","");    //Remove any additional } that may exist to help with the formating later
        D = "{" + D + "}";        //Add a { and } to reformat the line correctly from the splitting
    
        NewChartDataArray.push(D);    //Push the data to the array
      }
    
      chart.dataProvider = NewChartDataArray;    //Update graph data
      chart.validateData();    //Revalidate chart data
    }
    

如果我手动直接添加整个字符串,我的图表重置效果很好。这就是我试图用其他方法复制的。

如果有人能够指出我做错了什么,那么我将非常感激。如果您认为我可以更好地做到这一点,我也愿意接受任何建议。

1 个答案:

答案 0 :(得分:2)

工作小提琴

http://jsfiddle.net/Se2UE/2/

我改变的核心就在这里

var NewChartDataArray = [];
  for(i=0; i<CD.length; i++)
  {
    var D = CD[i];
    D = D.replace("{","");
    D = D.replace("}","");
    D = "{" + D + "}";

    NewChartDataArray.push(JSON.parse(D));
  }

将NewChartDataArray声明为数组而不是字符串然后将对象添加到数组。 你有一个字符串数组,你的库需要一个对象数组

参考this