jQuery dynamically add images to table

流过昼夜 提交于 2021-02-04 21:01:28

问题


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?


回答1:


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



回答2:


Try setting window.myTable or similar to the output of table(), and then edit the table by acessing it from window.myTable.

For adding the images, what I would instead recommend is just inserting:

var img = $('<img>');
img.attr('src', parseInt(cellId) + ".png");
img.appendTo(domCol);

Right before domRow.append(domCol); (I did not test this).




回答3:


Here is a simple code to add your images in each cell that its id correspond.

$('[id^=cell-]').each(function() {
  var curCell = $(this);
  curCell.html('<img src="' + curCell.attr('id').substring(5) + '.png">');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr><td id="cell-0">1</td><td id="cell-1">2</td></tr>
</table>


来源:https://stackoverflow.com/questions/37149418/jquery-dynamically-add-images-to-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!