Help with looping arrays into existing divs
I'm trying to call开发者_C百科 three different arrays to existing divs, the end result should show four boxes with information dynamically filled from javascript.
However it doesn't work, and only shows the results from my productDesc
array.
Here is my code:
var productNames = new Array();
productNames[0]="One";
productNames[1]="Two";
productNames[2]="Three";
productNames[3]="Four";
var productImages = new Array();
productImages[0]= "Image 1 here";
productImages[1]= "Image 2 here";
productImages[2]= "Image 3 here";
productImages[3]= "Image 4 here";
var productDesc= new Array();
productDesc[0]= "This is product One";
productDesc[1]= "This is product Two";
productDesc[2]= "This is product Three";
productDesc[3]= "This is product Four";
function createItems()
{
for (var i=0; i<productNames.length; i++) {
document.getElementById("product" + i).innerHTML = productNames[i];
document.getElementById("product" + i).innerHTML = productImages[i];
document.getElementById("product" + i).innerHTML = productDesc[i];
}
};
Here is the HTML
<body onload="createItems()">
<div id="product">
<span id="product0"></span>
<br/>
<a href="#">Buy</a>
</div>
<div id="product">
<span id="product1"></span>
<br/>
<a href="#">Buy</a>
</div>
<div id="product">
<span id="product2"></span>
<br/>
<a href="#">Buy</a>
</div>
<div id="product">
<span id="product3"></span>
<br/>
<a href="#">Buy</a>
</div>
</body>
Did you mean
var productNames = new Array();
productNames[0]="One";
productNames[1]="Two";
productNames[2]="Three";
productNames[3]="Four";
var productImages = new Array();
productImages[0]= "Image 1 here";
productImages[1]= "Image 2 here";
productImages[2]= "Image 3 here";
productImages[3]= "Image 4 here";
var productDesc= new Array();
productDesc[0]= "This is product One";
productDesc[1]= "This is product Two";
productDesc[2]= "This is product Three";
productDesc[3]= "This is product Four";
function createItems() {
for (var i=0; i<productNames.length; i++) {
document.getElementById("product" + i).innerHTML = productNames[i];
document.getElementById("product" + i).innerHTML += productImages[i];
document.getElementById("product" + i).innerHTML += productDesc[i];
}
};
精彩评论