简体   繁体   中英

How to add images as cells in table with Javascript

I'm trying to add an image to my table for each individual cell using Javascript as part of a Connect4 game that I have to create for my assignment. Could I please get some help with this?

Here's the function that I am trying to add the image in: (the stuff that's been commented out is what I've tried to use but failed

function generateTable()
    {
        var brd = document.getElementById("board");

        var x =document.createElement("IMG");
        x.setAttribute("src","block.png");
        x.setAttribute("height","10%");
        x.setAttribute("width","10%");
        x.setAttribute("alt","block.png");

        var body = document.getElementsByTagName("body")[0];

        var tbl = document.createElement("table");
        var tblBody = document.createElement("tbody");

        var maxCol= 7;
        var maxRow = 6;

        for(var x=0;x<maxRow;x++)
        {
            var row = document.createElement("tr");

            for(var y=0;y<maxCol;y++)
            {
                var cell = document.createElement("td") ;
            /*  cell= "<img src='board.png' alt='board' height='10%' width = '10%'>";*/
        /*   var cellImg= document.createElement("board");
                cell.appendChild(cellImg);*/
                            //var cellText = document.createTextNode("jhgfbcjk");
                            //cell.appendChild(x);

                row.appendChild(cell);
            }       

            tblBody.appendChild(row);           
        }

        tbl.appendChild(tblBody);
        body.appendChild(tbl);
        /*tbl.setAttribute("border","2");*/
}

Within your generateTable() function, try adding:

function generateTable()
{
    var whateverrow=document.getElementById("yourId").rows[0];
    x.innerHTML="<img src='URL' alt='whatever'/>";
}

This should set the inner HTML of a new cell to a HTML img element.

Use cell.innerHTML = '<img src="http://placehold.it/40x40?text=IMG" width="20" height="20" />';

 function generateTable() { var brd = document.getElementById("board"); var body = document.getElementsByTagName("body")[0]; var tbl = document.createElement("table"); var tblBody = document.createElement("tbody"); var maxCol = 7; var maxRow = 6; for (var x = 0; x < maxRow; x++) { var row = document.createElement("tr"); for (var y = 0; y < maxCol; y++) { var cell = document.createElement("td"); cell.innerHTML = '<img src="http://placehold.it/40x40?text=IMG" width="20" height="20" />'; row.appendChild(cell); } tblBody.appendChild(row); } tbl.appendChild(tblBody); brd.appendChild(tbl); } generateTable() 
 <div id="board"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM