图表js加号

Chart js adding number

我正在尝试更新圆环图中的数据,但在按下“添加数据”按钮时我的 addData 函数似乎不起作用。我想添加 "unknown" 作为数据为 8 的另一个标签。请帮忙。

 <DOCTYPE html>
<html>
<head>
 <title>ChartJS - Pie Chart</title>
    <script src="jquery-3.2.1.js"></script>
    <script 
 src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js">
 </script>
    <link rel="stylesheet" type="text/css" href="template.css">
 </head>
 <body>
 <div class="block">        
  <input type="button" value="Add Data" onclick="addData()">
 <canvas id="doughnut-chart" width="400" height="400"></canvas>
 <script>
 new Chart(document.getElementById("doughnut-chart"), {
 type: 'doughnut',
 data: {
  labels: ["Male", "Female"],
  datasets: [
    {
      label: "Population (millions)",
      backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
      data: [6,4]
    }
  ]
 },
 options: {
  title: {
    display: true,
    text: 'Predicted world population (millions) in 2050'
  }
 }
 });
function addData() {
Chart.data.datasets[0].data[2] = 8;
Chart.data.labels[2] = "Unknown";
Chart.update();
}
</script>
</div>
</body>
</html>

我在你的代码中收到一条相当不言自明的错误消息:

TypeError: Chart.data is undefined

库可以在同一文档中绘制多个图表。最简单的修复方法是将其存储在变量中:

var myDoughnutChart = new Chart(document.getElementById("doughnut-chart"), {
 type: 'doughnut',
 data: {
  labels: ["Male", "Female"],
  datasets: [
    {
      label: "Population (millions)",
      backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
      data: [6,4]
    }
  ]
 },
 options: {
  title: {
    display: true,
    text: 'Predicted world population (millions) in 2050'
  }
 }
 });
function addData(whatChart) {
  whatChart.data.datasets[0].data[2] = 8;
  whatChart.data.labels[2] = "Unknown";
  whatChart.update();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js"></script>

<div class="block">        
  <input type="button" value="Add Data" onclick="addData(myDoughnutChart)">
  <canvas id="doughnut-chart" width="400" height="400"></canvas>
</div>