jquery 图表
以下是关于使用 jQuery 实现图表的几种常见方法及示例代码:
使用 Chart.js 与 jQuery 结合
Chart.js 是一个流行的开源图表库,与 jQuery 兼容性良好。需引入 Chart.js 库后通过 jQuery 操作 DOM。
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
$(document).ready(function() {
const ctx = $('#myChart')[0].getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: 'Colors',
data: [12, 19, 3],
backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56']
}]
}
});
});
</script>
使用 Highcharts 与 jQuery
Highcharts 是功能强大的商业图表库,提供 jQuery 适配器。
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div id="container" style="width: 100%; height: 400px;"></div>
<script>
$(document).ready(function() {
$('#container').highcharts({
title: { text: 'Monthly Average Temperature' },
xAxis: { categories: ['Jan', 'Feb', 'Mar'] },
yAxis: { title: { text: 'Temperature (°C)' } },
series: [{
name: 'Tokyo',
data: [7.0, 6.9, 9.5]
}]
});
});
</script>
使用 jQuery Flot
Flot 是专为 jQuery 设计的纯 JavaScript 绘图库,适合简单图表需求。
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/jquery.flot.min.js"></script>
<div id="flot-chart" style="width: 400px; height: 300px;"></div>
<script>
$(document).ready(function() {
const data = [[0, 0], [1, 1], [2, 4], [3, 9]];
$.plot("#flot-chart", [data], {
series: { lines: { show: true }, points: { show: true } }
});
});
</script>
使用 Google Charts 与 jQuery
Google Charts 提供丰富的图表类型,可通过 jQuery 动态加载数据。
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div id="google-chart" style="width: 400px; height: 300px;"></div>
<script>
$(document).ready(function() {
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
const data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 8],
['Eat', 2]
]);
const chart = new google.visualization.PieChart($('#google-chart')[0]);
chart.draw(data, { title: 'Daily Activities' });
}
});
</script>
注意事项
- 确保引入的库版本兼容。
- 响应式设计需额外配置 CSS 或库参数。
- 动态数据更新时注意性能优化。
以上方法可根据项目需求选择,Chart.js 和 Highcharts 适用于复杂场景,Flot 适合轻量级需求,Google Charts 适合快速集成标准化图表。







