我正在尝试在动态填充的表格的每一行末尾添加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。有什么想法吗?
答案 0 :(得分:3)
$(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
}]);
});
&#13;
<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>
&#13;
答案 1 :(得分:2)
错误消息并不表示是否创建了span元素,它说代码无法找到sparkline
函数,以解决此问题
请确保:
jquery.sparkline.js
包含在您的网页中,即
迷你图的JavaScript文件存在。jquery
和{。}的顺序
jquery.sparkline.js
,首先加载jQuery
,然后加载sparkline
另请注意,jquery selector
始终返回类似于数组的jquery
对象,该对象与JavaScript createElement()
我的意思是:
var dataSpan = document.createElement('span');
dataSpan.sparkline(...)
与
不同$("#sparkline").sparkline(...)
建议您按jQuery
检索动态添加的元素,然后创建sparkline
图表。
或者,在创建元素集ID属性后如下
dataSpan.setAttribute("id", "yourRandomDynamicIdHere");
$("#yourRandomDynamicIdHere").sparkline(...)
希望这有帮助!