ChartJS 如何将嵌套函数传递给HTML按钮和下拉菜单

tag5nh1u  于 2022-11-07  发布在  Chart.js
关注(0)|答案(1)|浏览(143)

我有两个主要的函数getChart()和fetchdata(),它们分别从数据库中获取图表数据和我的x轴和y轴数据。我想使用我的getChart中的一个函数,当点击它们时,我的下拉菜单可以显示不同类型的图表。有人能帮我吗?谢谢

<body>
<div class="chartMenu">
    <p>Loan Applications Accepted</p>
    <div class="chartCard">
        <div class="chartBox">
            <canvas id="myChart"></canvas>

            <button onclick="(new getChart()).back();"> GO BACK </button>
            <select onchange="(new start()).changeChart();">
                <optgroup label="Select Chart"></optgroup>
                <option value="bar">Bar</option>
                <option value="pie">Pie</option>
                <option value="line">Line</option>
                 <option value="doughnut">Doughnut</option>
              </select>

函数fetchData(url){ $. AJAX ({ url:URL,键入:“GET”,

success: function (data) {
                        coordinates = [];
                        // console.log(data);
                        Array.from(data).forEach(element => {
                            coordinates.push({ x: element.x_axis, y: element.y_axis })
                            console.log(coordinates)

                        });

                        getChart();

                    },

                    error: function (error) {
                        console.log(`Error ${error}`);
                    }
                });

            };

函数getChart(){

//setup block
      var data = {

        datasets: [{
          label: 'No of Loan Applications',
          data: coordinates,

          backgroundColor: [
            'rgba(193, 32, 32, 0.58)',
            'rgba(75, 192, 192, 0.58)',
            'rgba(255, 159, 64, 0.58)',
            'rgba(153, 167, 64, 0.58)',
            'rgba(153, 102, 255, 0.58)',
            'rgba(255, 159, 64, 0.58)',
            'rgba(0, 0, 0, 0.58)',
            'rgba(167, 40, 145, 0.58)',
            'rgba(0, 184, 223, 0.58)',
            'rgba(70, 216, 59, 0.58)',
            'rgba(255, 231, 59, 0.58)',
            'rgba(18, 228, 184, 0.58)'

          ],
          borderColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(255, 159, 64, 1)',
            'rgba(75, 192, 192, 0.8)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)',
            'rgba(0, 0, 0, 0.2)',
            'rgba(167, 40, 145, 0.8)',
            'rgba(0, 184, 223, 0.8)',
            'rgba(70, 216, 59, 0.54)',
            'rgba(255, 231, 59, 0.86)',
            'rgba(18, 228, 184, 0.59)'
          ],
          borderWidth: 1
        }]

      };

      //config block
      var config = {
        type: 'bar',
        data,
        options: {

          scales: {
            y: {
              beginAtZero: true,
              grace: 1,
              ticks: {

                precision: 0,

              }

            },

          },

        }

      };

      //render block
      var ctx = document.getElementById('myChart');

      let myChart = new Chart(
        ctx,
        config

      );

      this.back = function () {
          if (myChart != null) {
              myChart.destroy();
          }
          fetchData('http://localhost:8080/jsonGet?year=1')
          myChart.data.datasets[0].data = coordinates;
          myChart.update();
      };

      function clickHandler(click) {

        const points = myChart.getElementsAtEventForMode(click, 'nearest', { intersect: true }, true);
        if (points.length) {
          const firstPoint = points[0];
          console.log(firstPoint.element.$context.raw.x)

          if (firstPoint.element.$context.raw.x == "2020") {

            fetchData('http://localhost:8080/jsonGet?year=2020')
            myChart.data.datasets[0].data = coordinates;
            myChart.update();

          }

          else if (firstPoint.element.$context.raw.x == "2021") {

            fetchData('http://localhost:8080/jsonGet?year=2021')
            myChart.data.datasets[0].data = coordinates;
            myChart.update();

          }

          else if (firstPoint.element.$context.raw.x == "2022") {

            fetchData('http://localhost:8080/jsonGet?year=2022')
            myChart.data.datasets[0].data = coordinates;
            myChart.update();

          }

          else {
            console.log("Wrong input");
          }

        }
      };
      ctx.onclick = clickHandler;

      function changeChart(chartType) {
        console.log(chartType);
        console.log(chartType.value);
      }

      function start() {
        getChart();
        clickHandler(click);
        changeChart(chartType)
      }

      start();

    };

    $(document).ready(fetchData(url));
lfapxunr

lfapxunr1#

下面是正在发生的事情。
您正在调用getChart()start()调用start(),而在start()中,您正在调用getChart()!!您正在进行无限递归,但它实际上在第二次调用getChart()时停止,因为图表没有被销毁。
首先,只需将每个函数都从getChart中取出,并删除递归。
现在,将select设置为以下内容:

<select id="types">

并在您的javascript中添加以下内容以接受change事件:

$(function () {
    // on change the type of the chart
    $(document).on("change", "#types", function () {
        let type = $('#types').val();
        changeChart(type);
    });
})

现在正在更改图表的类型。首先您需要销毁图表,然后您可以使用所选类型重新创建图表。

function changeChart(newType) {
    if (chart) {
        chart.destroy();
    }
    myChart= new Chart("myChart", {
        type: newType,
        .
        .
        .
    }
}

相关问题