Chart.js-从HTML获取数据

时间:2019-02-06 02:00:02

标签: jquery chart.js zepto

我能够检索条形图的data,但是无法将labelscolors与数据进行匹配。

如何更改功能,以便每个<canvas>都具有:

data-chart="[1,2,3]" 
data-label="[a,b,c]"
data-color="[red,blue,green]"

数据点返回为:

a = 1 color is red,
b = 2 color is blue,
c = 3 color is green

现在,标签和颜色与数据点不匹配。

$(document).ready(function() {
  var barStyle = {
    scaleLineColor: "rgba(0,0,0,0)",
    scaleShowLabels: true,
    scaleShowGridLines: false,
    pointDot: false,
    datasetFill: false,
    // Sadly if you set scaleFontSize to 0, chartjs crashes
    // Instead we'll set it as small as possible and make it transparent
    scaleFontSize: 9,
  };
  $(".barchart").each(function() {
    //Get context with jQuery - using jQuery's .get() method.
    var ctx = $(this)
      .get(0)
      .getContext("2d");
    //This will get the first returned node in the jQuery collection.
    var myNewChart = new Chart(ctx);

    // Get the chart data and convert it to an array
    var chartData = JSON.parse($(this).attr("data-chart"));

    // Build the data object
    var data = {};
    var labels = [];
    var datasets = {};

    // Create a null label for each value
    for (var i = 0; i < chartData.length; i++) {
      labels.push("");
    }

    // Create the dataset
    datasets["strokeColor"] = $(this).attr("data-color");
    datasets["data"] = chartData;

    // Add to data object
    data["labels"] = $(this).attr("data-label");
    data["datasets"] = Array(datasets);

    new Chart(ctx).Bar(data, barStyle);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/zepto/1.0/zepto.min.js"></script>

<canvas id="myChart" width="200" height="100" class="barchart" data-chart="[200,25,90,214,96,27,210]" data-label="[One,Two,Three,Four,Five,Six,Seven]" data-color="['rgba(255, 99, 132, 0.2)','rgba(54, 162, 235, 0.2)','rgba(255, 206, 86, 0.2)','rgba(75, 192, 192, 0.2)','rgba(153, 102, 255, 0.2)','rgba(255, 159, 64, 0.2)']"></canvas>

1 个答案:

答案 0 :(得分:1)

我看到从HTML数据属性中获取数据时存在一些问题,代码l # $`Q1` # question label value # 1 Q1 yes 1 # 2 Q1 no 2 # $`Q2` # question label value question label value # 3 Q2_1 yes 3 Q2_2 yes 3 # 4 Q2_1 no 1 Q2_2 no 2 # $`Q3` # question label value question label value question label value # 1 Q3_1 yes 2 Q3_2 yes 3 Q3_3 yes 2 # 2 Q3_1 yes 2 Q3_2 yes 3 Q3_3 yes 2 # $Q4 # question label value # 11 Q4 x 2 应该为$(this).attr("data-label"),这样它才能正确给出值。

我还在您的代码中做了一些其他改进,请参见小提琴-> https://jsfiddle.net/pjr5wuft/3/或下面的代码。

$(this).data("label")