我正在尝试更新甜甜圈图中的数据,而在按"添加数据"按钮时,我的AddData功能似乎不起作用。我想将"未知"添加为具有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是未定义的
库可以在同一文档中绘制多个图表。最简单的修复是将其存储在变量中:
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>