我正在使用jQuery将JSON对象中的值注入到现有的空表中。
我想要做的是从上到下填充我的桌子,而不是现在从左到右。那么我如何修改这个片段来完成我想要的呢?
_.each(dataset, function(v, k){
$("tr td:empty:first", "#myTable tbody").html("<strong>"+v+"</strong>");
});
我想有可能将td定位在填充行最少的列中,但是如何?
答案 0 :(得分:1)
将您的选择器更改为:
$("tr td:empty:first:first-child", "#myTable tbody")
因此只有当表格单元格是其父级的第一个子节点时才匹配,因此只会插入第一列。
编辑:一种基于已知且有限数量的列填充表格的方法
它的工作原理是使用每行的nth-child
选择每个表列,然后将列连接在一起,并过滤第一个空列。
var cells = [].concat(
$('tr td:nth-child(1)').get(),
$('tr td:nth-child(2)').get(),
$('tr td:nth-child(3)').get(),
$('tr td:nth-child(4)').get()
)
_.each(dataset, function(v, k){
$(cells).filter(':empty:first').html("<strong>"+v+"</strong>");
});
编辑:通用版
// create array to hold cells ordered by column
var cells = [];
// loop through desired columns adding to cells array
// hint: you can specify column `from` and `to` in the for loop definition
for(i=1;i<=4;i++)
cells = cells.concat($('tr td:nth-child('+i+')').get());
// loop through the data, populating each column in order
_.each(dataset, function(v, k){
$(cells).filter(':empty:first').html("<strong>"+v+"</strong>");
});
答案 1 :(得分:0)
dataset
是一个数组吗?如果是这样的话,那就是:
var self;
$('#myTable tr:has("td:empty")', function (index, elem) {
if (index < dataset.length) {
self = $(this);
self.find('td:empty').html("<strong>"+dataset[i]+"</strong>")
}
});
..弗雷德里克
答案 2 :(得分:0)
以下是我最终要做的事情,使用underscore.js
来迭代数据集:
var currentCol = 0;
var currentRow = 0;
var renderedCount = 0;
_.each(dataset, function(v, k) {
/* Switch to a new column when we have rendered enough (4)
* elements vertically per column and reset the rowcounter.
*/
if (renderedCount % 4 === 0) {
currentCol++;
currentRow = 0;
}
// Inject our value as HTML into the first empty TD per column
$("tr:eq("+currentRow+") td:empty:first", "#mytable tbody").html(v);
// Increment current row count and our renderedCount
currentRow++;
renderedCount++;
});
非常感谢@BillyMoon提供帮助!
<强>更新强>
要在执行上述操作之前创建空表,我这样做了:
// To allow repeating strings (n) times. Borrowed from someone on SO
String.prototype.repeat = function( num ) {
return new Array( num + 1 ).join( this );
}
// Setup our wanted maximum amount of columns horizontally and our table structure
var maxColsPerRow = 4;
var rowHTML = "<tr>"+'<td></td>'.repeat(maxColsPerRow)+"</tr>";
var datasetCount = _.keys(dataset).length; // Amount of properties in our dataset calculated with underscore.js keys()-method.
// Append as many empty rows&cells to our table that we'll need
$("#myTable tbody").html( rowHTML.repeat( Math.round( datasetCount/maxColsPerRow));