jQuery动态添加图片到表格 [英] jQuery dynamically add images to table

查看:33
本文介绍了jQuery动态添加图片到表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

HTML:

Javascript

 函数表() {变量 i,X,domRow,domCol,行 = $("#rows").val(),colums = $("#columns").val(),table = $(''),细胞 ID = 0;table.empty();for(i = 0; i <行; i++) {domRow = $('');for(x = 0; x <列; x++) {domCol = $('<td/>',{'id': "cell-" + cellId++,'class': "单元格",'文本':'单元格','数据行':我,'数据列':x});domRow.append(domCol);}table.append(domRow);}返回表;}

现在我想从另一个函数向每个数据单元格添加图像.示例:

function images() {var game = $("game");//TODO 图片也需要添加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` 是 <td>元素 jQuery 当前附加到var num = this.id.split('-')[1];return '<img src="' + num + '.png"/>';});game.append(tableEl)}

I need to add images to a given table. I have the following code:

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;
}

Now I want do add images to each data cell from another function. Example:

function images() {
    var game = $("game");

    // TODO the images need to be added too
    game.append(table())
}

An image with the name 0.png needs to be added to the data cell with the id="cell-0" and so on... (1.png to id="cell-1")

How could I do this?

解决方案

The jQuery append method can take a function that returns the HTML string to append. And within that function this refers to the element. So you can just find all the td elements in your table and append the right image to each one:

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)
}

这篇关于jQuery动态添加图片到表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆