单击按钮后如何更新变量

时间:2019-01-26 19:33:25

标签: javascript jquery chart.js

我只是不知道如何单击按钮,然后将另一个数据集传递给变量,以便在按下特定按钮后动态更新Chart.js图。我来自python,最近才开始学习js,此类代码通常在python中有效。请查看我的代码

<div id="parentElementID">
    <button type="button" id="1">Button1</button>
    <button type="button" id="2">Button2</button>
    <button type="button" id="3">Button3</button>
</div>

<div class="container">
    <canvas id="myChart"></canvas>
</div>

<script type="text/javascript">
    var spins15 = [1, 1, 1]
    //These should update the value of a variable on click. But apparently they don't
    $(document).ready(function(){
        $('#1').click(function(){
            spins15=[15, 25, 35];
            });
        });

    $(document).ready(function(){
        $('#2').click(function(){
            spins15=[25, 31, 24];
            });
        });

    $(document).ready(function(){
        $('#3').click(function(){
            spins15=[50, 11, 25];
            });
        });
    //Chart.js part
    let myChart = document.getElementById('myChart').getContext('2d');
    var options = {
        responsive: true,
        maintainAspectRatio: true,
        };

    let someChart = new Chart(myChart, {
        type:'bar',
        data:{
            labels:['0', '32', '15'],

            datasets:[{
                label:'Some chart',
                //This variable below should be updated in order to update the barchart
                data:spins15
            }]
        },
        options:options
    });

    //

</script>

3 个答案:

答案 0 :(得分:1)

我认为这是您所需要的:

function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
    dataset.data.push(data);
});
chart.update();}

function removeData(chart) {
chart.data.labels.pop();
chart.data.datasets.forEach((dataset) => {
    dataset.data.pop();
});
chart.update();}

Source: Updating Charts

答案 1 :(得分:0)

每次更改数据时,都需要调用对象方法 .update(),以更新图形的可视化效果。 看看Chartjs库的文档:https://www.chartjs.org/docs/latest/developers/updates.html

答案 2 :(得分:0)

原始文档:https://www.chartjs.org/docs/latest/developers/api.html#updateconfig

示例:

 $('#1').click(function () {
    spins15 = [15, 25, 35];
    someChart.data.datasets[0] = spin;
    someChart.update();
});