我需要将图像添加到给定的表格中。我有以下代码:
HTML:
<div class="container" id="game"></div>
Javascript
function table() {
var i,
x,
domRow,
domCol,
rows = $("#rows").val(),
colums = $("#columns").val(),
table = $('<table>'),
cellId = 0;
table.empty();
for(i = 0; i < rows; i++) {
domRow = $('<tr/>');
for(x = 0; x < colums; x++) {
domCol = $('<td/>',{
'id': "cell-" + cellId++,
'class': "cell",
'text': 'cell',
'data-row': i,
'data-col': x
});
domRow.append(domCol);
}
table.append(domRow);
}
return table;
}
现在我想从另一个函数向每个数据单元格添加图像。 示例:
function images() {
var game = $("game");
// TODO the images need to be added too
game.append(table())
}
需要将名称为 0.png 的图像添加到 id="cell-0"的数据单元格中,依此类推...(1.png 到 id="cell-1")
我该怎么做?
最佳答案
jQuery append
方法可以采用一个返回要附加的 HTML 字符串的函数。在该函数中,this
指的是元素。因此,您可以在表格中找到所有 td
元素,并将正确的图像附加到每个元素:
function images() {
var game = $("game");
var tableEl = table();
tableEl.find('td').append(function () {
// `this` is the <td> element jQuery is currently appending to
var num = this.id.split('-')[1];
return '<img src="' + num + '.png" />';
});
game.append(tableEl)
}
关于javascript - jQuery动态添加图片到表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37149418/