如何在ChartJS实例中替换myChart["data"]
?
我从后端收到两组数据。我可以用myChart["data"]["datasets"][0]["data"] = [1,2,3];
而不是整个数据对象交换单个数据点。那是为什么?
以下代码不起作用(请参阅"此操作无效"代码中的注释)。
HTML:
<div class="col s12 m6 l8">
<span id="control1">UMSCHALTER</span>
<canvas id="kontakteChart" width="600" height="300"></canvas>
</div> <!-- col -->
进口/ VERSION:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.min.js" type="text/javascript"></script>
JS:
// Supplied Datasets to display
var data1 = {"labels": ["1", "2", "3"], "datasets": [{"label": "Contacts", "data": [20, 15, 10], "backgroundColor": "rgba(255, 99, 132, 0.2)", "borderColor": "rgba(255,99,132,1)", "borderWidth": 1}]};
var data2 = {"labels": ["1", "2", "3"], "datasets": [{"label": "Contacts", "data": [10, 23, 41], "backgroundColor": "rgba(255, 99, 132, 0.2)", "borderColor": "rgba(255,99,132,1)", "borderWidth": 1}]};
// Draw the initial chart
var kChartCanvas = $("#kontakteChart");
var myChart = new Chart(kChartCanvas, {
type: 'bar',
data: data1,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
// Called on Click
function chartContent(){
console.log(myChart["data"]);
myChart["data"] = data2; // <<<<------ THIS DOES NOT WORK.
myChart.update();
}
// Set the listener for the click function
$(document).ready(function() {
$( "#control1" ).click(chartContent);
});
答案 0 :(得分:1)
设置 myChart["config"]["data"] = data2
// Supplied Datasets to display
var data1 = { "labels": ["1", "2", "3"], "datasets": [{ "label": "Contacts", "data": [20, 15, 10], "backgroundColor": "rgba(255, 99, 132, 0.2)", "borderColor": "rgba(255,99,132,1)", "borderWidth": 1 }] };
var data2 = { "labels": ["1", "2", "3"], "datasets": [{ "label": "Contacts", "data": [10, 23, 41], "backgroundColor": "rgba(255, 99, 132, 0.2)", "borderColor": "rgba(255,99,132,1)", "borderWidth": 1 }] };
// Draw the initial chart
var kChartCanvas = $("#kontakteChart")[0].getContext('2d');
var myChart = new Chart(kChartCanvas, {
type: 'bar',
data: data1,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
// Called on Click
function chartContent() {
myChart["config"]["data"] = data2; //<--- THIS WORKS!
myChart.update();
}
// Set the listener for the click function
$(document).ready(function() {
$("#control1").click(chartContent);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="kontakteChart"></canvas>
<button id="control1">UMSCHALTER</button>
&#13;