使用chart.js进行jQuery加载 [英] jquery load with chart.js

查看:119
本文介绍了使用chart.js进行jQuery加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JQuery Load加载页面的一部分,并希望使用chart.js插件将图表构建为页面的一部分.如果刷新页面,则html加载会很好,并且图表会生成,但仅在某些情况下,它不会在加载第一页时构建图表.我需要在这里推迟还是答应?

I'm loading parts of a page with JQuery Load and want to use chart.js plugin to build a chart as part of a page. The load html loads fine and the chart will build if you refresh the page, but only sometimes, it never builds the chart on first page load. Do I need a defer or promise here?

推荐答案

是的,如果您正在使用jQuery .load()使用canvas元素加载HTML,则需要将图表初始化放在完整的回调中,就像这样

Yes, if you are loading the HTML with the canvas element using jQuery .load(), you need to put the chart initialization in the complete callback, like so

$("#result").load("canvas.html", function () {
    var data = {
        labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
        datasets: [
            {
                data: [12, 23, 23, 43, 45, 12, 33]
            }
        ]
    };

    var ctx = document.getElementById("myChart").getContext("2d");
    var myLineChart = new Chart(ctx).Line(data);
});

canvas.html在哪里

where canvas.html is

<canvas id="myChart" height="300" width="500"></canvas>


加载数据时canvas元素需要具有非零的渲染大小,否则该图表将不会显示.


The canvas element needs have a non-zero render size when the data is loaded, otherwise the chart won't show up.

在大多数情况下,将new Chart...放在正确的位置即可(例如,在回调中,选项卡可见后等).如果无法确定这样的点,请使用具有足够延迟的setTimeout来确保呈现canvas元素.

In most cases, putting the new Chart... in the right place (for e.g. in the callback, after a tab is visible, etc.) will be enough. When it's not possible to identify such a point, using a setTimeout with enough delay to guarantee that the canvas element is rendered will work.

这篇关于使用chart.js进行jQuery加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆