问题描述
我正在使用 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>
加载数据时画布元素需要具有非零渲染大小,否则图表不会显示.
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
来保证画布元素被渲染会起作用.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!