将图像附加到没有 id 或值的 td 元素

Append image to td element with no id or value

本文关键字:td 元素 id 图像      更新时间:2023-09-26

我有一个图像元素数组,我使用一个函数来随机化数组,我想将它们按随机顺序追加回 HTML 表。但是,我试图避免为每个 td 元素提供自己的 id,因为有很多......我想知道是否可以在没有 id 的情况下将图像附加到 td 元素。

HTML 表大约有 12 行,如下所示:

    <table class="piecetray">
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
    etc...

.JS

function randomizePieces(myArray) { 
  for (var i = myArray.length - 1; i > 0; i--) { 
    var j = Math.floor(Math.random() * (i + 1)); 
    var temp = myArray[i]; 
    myArray[i] = myArray[j]; 
    myArray[j] = temp; 
  } 
return array; 
}

假设表已经构建,并且您希望遍历每个td并使用普通的 js 更新其背景。

// lets start by getting the `table` element
var tbl = document.getElementsByClassName("piecetray");
// lets get all the child rows `tr` of the `table`
var trs = tbl[0].childNodes[1].getElementsByTagName("tr");
var trlen = trs.length;
//just a test image 
var host = "http://upload.wikimedia.org";
var img = host + "/wikipedia/commons/thumb/2/25/Red.svg/200px-Red.svg.png";
// iterate over the rows `tr`
for (var i = 0; i < trlen; i++) {
    //get the `td`s for this row
    var tds = trs[i].getElementsByTagName("td");
    var tdlen = tds.length;
    //iterate over the cells `td`
    for (var n = 0; n < tdlen; n++) {
        //set `backgroundImage`
        tds[n].style.backgroundImage = "url('"" + img + "'")";
    }
}

请参阅 JSFiddle,希望这至少为您指明了正确的方向。

我相信

这是您正在寻找的基本思想。

$('#table').html(''); //clear the table
for(var x = 0, len = array.length; x < len; x++){ //fill the table
  $('#table').append('<tr>');
  $('#table').append('<td>' + array[x] + '</td>'); //can also add img tag here if you get the SRC for the image
  $('#table').append('</tr>');
}
<table id="table"></table>

会是这样的吗

$(document).ready(function(e) {
$.each($('.piecetray tr td'), function(index, value){
    var img = $('<img />').attr('src', '').attr('title', index);
        $(value).append(img);
});

});

演示