我正在尝试添加 sparkline chart在我动态填充的表的每一行的末尾。这是我的代码:
function populateOverallOverview(result){
var table = document.getElementById("firstTabOverall");
function addCell(tr, text) {
var td = tr.insertCell();
td.textContent = text;
return td;
}
result.forEach(function (item) {
// sparkline chart here
var dataSpan = document.createElement('span');
dataSpan.sparkline(amountData, {
type: 'bar',
barColor: '#191919'});
var row = table.insertRow();
addCell(row, item.category);
addCell(row, '$ ' + item.currentMonthAmt.toFixed(2));
addCell(row, item.topMonthStr + ' ($ ' + item.topAmount.toFixed(2) + ')');
});
}
amountData 的示例数据是 [5,6,7,2,0,-4,-2,4]。我的 HTML 表格:
<table id="firstTabOverall" class="table" style="font-size:13px">
<tr>
<th>Category <span id="sparkline1"></span></th>
<th>Current Month Revenue</th>
<th>Best Selling Month</th>
</tr>
</table>
我正在尝试动态创建迷你图,然后将其添加到该行的末尾。但是,我收到此错误消息:
Uncaught (in promise) TypeError: dataSpan.sparkline is not a function
我不确定如何使用 ID 动态创建跨度,然后将该 ID 用于 .sparkline。有什么想法吗?
最佳答案
$(document).ready(function() {
var amountData = [5, 6, 7, 2, 0, -4, -2, 4];
function populateOverallOverview(result) {
var table = document.getElementById("firstTabOverall");
function addCell(tr, text) {
var td = tr.insertCell();
td.textContent = text;
return td;
}
result.forEach(function(item) {
var row = table.insertRow();
addCell(row, item.category);
addCell(row, '$ ' + item.currentMonthAmt.toFixed(2));
addCell(row, item.topMonthStr + ' ($ ' + item.topAmount.toFixed(2) + ')');
var lastCell = addCell(row, ""); //Added blank cell for sparkline
var dataSpan = $("<span>");
dataSpan.appendTo(lastCell);
dataSpan.sparkline(amountData, {
type: 'bar',
barColor: '#191919'
});
});
}
populateOverallOverview([{
category: "Transportation",
currentMonthAmt: 1,
topMonthStr: 1,
topAmount: 1
}, {
category: "Healthcare",
currentMonthAmt: 1,
topMonthStr: 1,
topAmount: 1
}]);
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-sparklines/2.1.2/jquery.sparkline.min.js"></script>
</head>
<body>
<table id="firstTabOverall" class="table" style="font-size:13px">
<tr>
<th>Category</th>
<th>Current Month Revenue</th>
<th colspan=2>Best Selling Month</th>
</tr>
</table>
</body>
</html>
关于javascript - 将迷你图添加到动态填充的 HTML 表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46172695/