2016-12-26 81 views
-1

我正在嘗試將圖像存儲在使用javascript的數組中。我也想從該陣列中的每個圖像分配到一個下拉列表中的選項。這些圖像位於不同的服務器上。如何將圖像存儲在數組中(javascript)?

無論我嘗試什麼,我的功能都不起作用。有人可以幫助我嗎?

P.S - 在這種情況下,我只允許使用JavaScript(作業:/),我必須使用數組來存儲圖像。

HTML代碼:

<form action="#" method="get" accept charset="utf-8"> 

<select id="car"> 

<option> BMW </option> 
<option> Mercedes </option> 
<option> Audi </option> 
<option> VW </option> 

</select> 

<input type="button" value="select" onclick="myFunction();"> 

</form> 

Javascript代碼:

function myFunction() { 

var pictures = new Array(); 

pictures[0] = "https://pixabay.com/p-848904/?no_redirect"; 
pictures[1] = "http://www.pruebas.pieldetoro.net/web/MERCEDES/DOSSIERES/w115/8-1.jpg"; 
pictures[2] = "https://pixabay.com/p-1203738/?no_redirect"; 
pictures[3] = "https://cdn.pixabay.com/photo/2015/11/13/13/45/vw-beetle-1042002_960_720.jpg"; 

var index = document.getElementById('car').selectedIndex; 

document.images[0].src="https://pixabay.com/p-848904/?no_redirect" + pictures[index] + ".jpg"; 

}

謝謝您的解答!

+1

爲什麼你要爲源有兩個鏈接? –

+0

Ooops。我的錯。忘記了它。它應該與數組中的第一個元素相同。 – JavaApprentice

+0

同樣,您仍然使用兩個鏈接設置源。如果index = 0,那麼你的源代碼鏈接就是'https://pixabay.com/p-848904/?no_redirecthttps://pixabay.com/p-848904/?no_redirect.jpg「。這是故意的嗎? –

回答

0

這個代碼應工作:

function myFunction() 
{ 
    var pictures = [ 
     "https://pixabay.com/p-848904/?no_redirect", 
     "http://www.pruebas.pieldetoro.net/web/MERCEDES/DOSSIERES/w115/8-1.jpg", 
     "https://pixabay.com/p-1203738/?no_redirect", 
     "https://cdn.pixabay.com/photo/2015/11/13/13/45/vw-beetle-1042002_960_720.jpg" 
    ]; 
    var index = document.getElementById('car').selectedIndex; 
    document.getElementById('img1').src = pictures[index]; 
+0

剛剛嘗試過,但它仍然無效:/ 爲什麼你有'img1'?這是從哪裏來的? – JavaApprentice

+0

你只需要在你的表單後添加下面這行:

+0

@JavaApprentice再次看到你不知道'img1'是什麼...我建議你做一些研究並學習javascript的基礎知識。別人沒有爲你做功課。 – NewToJS

相關問題