2015-02-11 69 views
0
<div id="images"> 
    <img src="a.jpg" alt="" id="newImg"> 
</div> 

<button onclick="prevImage('newImg')">Prev</button> 
<button onclick="nextImage('newImg')">Next</button> 

<script> 
var imgArray = new Array(); 

imgArray[0] = new Image(); 
imgArray[0].src = 'a.jpg'; 

imgArray[1] = new Image(); 
imgArray[1].src = 'b.jpg'; 


function nextImage(element) 
{ 
    var img = document.getElementById(element); 

    for(var i = 0; i < imgArray.length;i++) 
    { 
     if(imgArray[i].src == img.src) 
     { 
      if(i === imgArray.length){ 
       document.getElementById(element).src = imgArray[0].src; 
       break; 
      } 
      document.getElementById(element).src = imgArray[i+1].src; 
      break; 
     } 
    } 
} 

function prevImage(element) 
{ 
    var img = document.getElementById(element); 

    for(var i = imgArray.length; i > 0; i--) 
    { 
     if(imgArray[i].src == img.src) 
     { 
      if(i === imgArray.length-1){ 
       document.getElementById(element).src = imgArray[0].src; 
       break; 
      } 
      document.getElementById(element).src = imgArray[i-1].src; 
      break; 
     } 
    } 
} 

如何從圖像陣列在javascript

這裏在上面的代碼中顯示前一個圖像,當我點擊下一個按鈕的下一個圖像被從陣列..similarly顯示如果我點擊PREV鍵的從當前圖像之前的形象應該是displayed..i都試過,但前面的功能無法正常工作任何人都可以幫助我

+0

for(var i = imgArray.length; i> 0; i--)應該是for(var i = imgArray.length-1; i> 0; i--) – 2015-02-11 05:04:23

+0

謝謝@RTPMatt它工作正常.. – karthik 2015-02-11 05:07:26

回答

2

在功能NEXTIMAGE()與更換循環: for(var i = 0; i < imgArray.length-1;i++) 和功能PREVIMAGE()取代循環: for(var i = imgArray.length-1; i > 0; i--)