问题描述:

<img> element is always empty. I've tried creating different loops and using other methods, but nothing seems to fix the error. Any ideas?

<script type="text/javascript">

var cards = new Array();

for(i = 0; i > 11; i++) {

cards[i] = new Image();

cards[i].src = "imgs/CardBack.jpg";

document.theImage.src == cards[i].src;

}

</script>

</head>

<body>

<table border="1" width="200px" height="400px">

<tr>

<td><img name="theImage"></td>

<td></td>

<td></td>

</tr>

<tr>

<td></td>

<td></td>

<td></td>

</tr>

<tr>

<td></td>

<td></td>

<td></td>

</tr>

</table>

网友答案:

in order to access src attribute of "theImage", I suggest you document.getElementsByName('theImage')[0].setAttribute('src', cards[i].src);.

Edit : Complete solution after bug tracking here : https://jsfiddle.net/oqbkhb64/2/

Cheers

网友答案:

Code has a few errors, try the following

var cards = new Array();
for (var i = 0; i < 11; i++) {
    cards[i] = new Image();
    cards[i].src = "imgs/CardBack.jpg"
    document.theImage.src = cards[i].src;
}

Hope it works

网友答案:

You can use getelementsByTagName() method to get all the <td> elements, and then in a loop create an image and assign it to each td:

HTML:

<table border="1" width="200px" height="400px" id="myTable">
<tr>
    <td></td>
    <td></td>
    <td></td>
</tr>
<tr>
    <td></td>
    <td></td>
    <td></td>
</tr>
<tr>
    <td></td>
    <td></td>
    <td></td>
</tr>
</table>

Javascript:

var table = document.getElementById("myTable"); 
var cells = table.getElementsByTagName("td"); 
for (var i = 0; i < cells.length; i++) { 
   var img=document.createElement("img");
   img.src="imgs/CardBack.jpg";
   cells[i].appendChild(img);     
}

This is a DEMO Fiddle.

相关阅读:
Top