django 将列表传递给js以显示图表

lawou6xi  于 2022-12-24  发布在  Go
关注(0)|答案(1)|浏览(133)

嗨,我是新来的Js,我有一些问题,显示我的图表属性。我试图传递一个列表到模板,然后抓住我的js scrpit,最后传递该列表显示图表。
我的模板里有这个标签:

<div style="display: none" id="listData" listmonth="{{ month_profit_list }}"></div>

然后传递到js文件,如下所示:

var ctx1 = $("#worldwide-sales").get(0).getContext("2d");
const div1 = document.getElementById('listData');
var listMonth = div1.getAttribute('listmonth');
console.log(listMonth)
var myChart1 = new Chart(ctx1, {
    type: "bar",
    data: {
        labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul","Ago","Sep","Oct","Nov","Dec"],
        datasets: [{
                label: "USA",
                data: listMonth,
                backgroundColor: "rgba(0, 156, 255, .7)"
            },
           
        ]
        },
    options: {
        responsive: true
    }
});

我的列表很好,在cosole中的输出是= [129,-69,226,25,151,114,-79,4,49,61,-76,65],但是我得到了这个图表:

你知道我做错了什么吗?

4uqofj5v

4uqofj5v1#

我在w3schools chartjs tryit playground中复制了您的代码,并对原始示例进行了如下修改:

<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<body>

<canvas id="myChart" style="width:100%;max-width:600px"></canvas>

<script>
var xValues = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul","Ago","Sep","Oct","Nov","Dec"];
var yValues = [129, -69, 226, 25, 151, 114, -79, 4, 49, 61, -76, 65];

new Chart("myChart", {
  type: "bar",
  data: {
    labels: xValues,
    datasets: [{
      label: "USA",
      backgroundColor: "rgba(0, 156, 255, .7)",
      data: yValues
    },]
  },
  options: {
    responsive: true
  }
});
</script>

</body>
</html>

而且效果很好

除非我错过了什么,否则可能是因为一些外部代码/设置,比如画布上的代码/设置(我不知道CSS的某个部分是否会干扰库),或者listMonth变量在控制台中显示良好,但在传入之前需要清理?

相关问题