代码之家  ›  专栏  ›  技术社区  ›  coopwatts

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

  •  1
  • coopwatts  · 技术社区  · 11 年前

    我有一个图像元素数组,我使用一个函数来随机化数组,我想将它们按随机化顺序追加到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; 
    }
    
    3 回复  |  直到 11 年前
        1
  •  0
  •   Sphvn Frebin Francis    11 年前

    假设已经构建了表,并且您希望遍历每个表 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 希望这至少能给你指明正确的方向。

        2
  •  0
  •   Joe Packer    11 年前

    我相信这是你要找的东西的基本概念。

    $('#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>
        3
  •  0
  •   mike123    11 年前

    是那样的吗

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

    });

    DEMO

    推荐文章