簡體   English   中英

將圖像附加到沒有id或值的td元素

[英]Append image to td element with no id or value

我有一個圖像元素數組,我使用一個函數對數組進行隨機化,我想將它們按隨機順序添加回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; 
}

我相信這是您要尋找的基本概念。

 $('#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);
});

});

DEMO

假設表已經構建,並且您要遍歷每個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 ,希望這至少可以為您指明正確的方向。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM