javascript - jQuery动态添加图片到表格

标签 javascript jquery

我需要将图像添加到给定的表格中。我有以下代码:

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/

相关文章:

javascript - 倒数计时器加快

internet-explorer - 字符串上的 jQuery 选择器不适用于 Internet Explorer

javascript - 将值添加到文本输入后数字不会改变

javascript - jQuery resize() 使用浏览器最大化按钮

JQuery UI 日期选择器在 Chrome 中无法工作

javascript - Colorbox JQuery 单击时未打开

javascript - 正确处理 HTML5 Canvas 引擎的时序

javascript - 根据 DIV 的数量更改 DIV 类

javascript - 当我有一个代表 JS 函数的对象时,Java Nashorn 在 Java 中创建 JS 对象

javascript - 可调整大小的 <a> 元素