我正在編碼一個包含多個圖像交換的頁面。我想交換兩張不同的圖像,但是其中只有一張正在工作,因爲圖像iD對於所有圖像都是相同的。從Javascript陣列中交換圖像
我不擅長JavaScript,似乎無法找到解決方法。任何幫助將非常感激。
var imgArray = new Array(
'/en_us/local/page_specific/furniture/dining-rustique-main.jpg',
'/en_us/local/page_specific/furniture/dining-rustique-main2.jpg',
'/en_us/local/page_specific/furniture/dining-bonnie-main.jpg',
'/en_us/local/page_specific/furniture/dining-bonnie-main2.jpg'
);
var imgPath = "";
function swapImage(imgID, obj) {
var theImage = document.getElementById('theImage');
var newImg;
newImg = imgArray[imgID];
theImage.src = imgPath + newImg;
obj.src = imgPath + imgArray;
}
function preloadImages() {
for (var i = 0; i < imgArray.length; i++) {
var tmpImg = new Image;
tmpImg.src = imgPath + imgArray[i];
}
}
<table cellspacing="0" cellpadding="3" width="100%">
<tr>
<td rowspan="2">
<div id="image"><img id="theImage" src="http://www.urbanbarn.com/images/urbanbarn/en_us/local/page_specific/furniture/dining-bonnie-main.jpg"></td>
<td valign="top"><img src="http://www.urbanbarn.com/images/urbanbarn/en_us/local/page_specific/furniture/dining-bonnie-gif.gif"></td>
</tr>
<tr>
<td valign="top"><img src="http://www.urbanbarn.com/images/urbanbarn/en_us/local/page_specific/furniture/trail-brown.jpg" onmouseover="swapImage(3)"><img src="http://www.urbanbarn.com/images/urbanbarn/en_us/local/page_specific/furniture/trail-grey.jpg" onmouseover="swapImage(2)"></td>
</tr>
<tr>
<td rowspan="2">
<div id="image"><img id="theImage" src="http://www.urbanbarn.com/images/urbanbarn/en_us/local/page_specific/furniture/dining-rustique-main.jpg"></td>
<td valign="top"><img src="http://www.urbanbarn.com/images/urbanbarn/en_us/local/page_specific/furniture/dining-rustique-gif.gif"></td>
</tr>
<tr>
<td valign="top"><img src="http://www.urbanbarn.com/images/urbanbarn/en_us/local/page_specific/furniture/rustique-sample-dark.jpg" onmouseover="swapImage(1)"><img src="http://www.urbanbarn.com/images/urbanbarn/en_us/local/page_specific/furniture/rustique-sample-pine.jpg"
onmouseover="swapImage(0)"></td>
</tr>
</table>
ID應該是唯一的,但你可以使用類多次。使用不同的ID –
您仍然可以使用getElementById,但使用傳入的圖像ID作爲參數來隔離圖像 –
Hello Rachel,感謝您的回覆。我如何創建不同的ID? – user3227561