如何在javascript中显示来自图像数组的先前图像

时间:2022-12-12 00:28:08
<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;
        }
    }
}

here in the above code when i click next button the next image is displayed from the array ..similarly if i click the prev button the previous image from the current image should be displayed..i have tried but the previous function is not working can anyone help me out

在上面的代码中,当我单击下一个按钮时,下一个图像将从数组中显示..同样,如果我单击上一个按钮,应显示当前图像中的上一个图像..我已经尝试但是之前的功能不起作用可以任何人帮助我

1 个解决方案

#1


2  

In function nextImage() replace the loop with: for(var i = 0; i < imgArray.length-1;i++) and in function prevImage()replace the loop with : for(var i = imgArray.length-1; i > 0; i--)

在函数nextImage()中用以下代码替换循环:for(var i = 0; i 0;我 - ) ;>

#1


2  

In function nextImage() replace the loop with: for(var i = 0; i < imgArray.length-1;i++) and in function prevImage()replace the loop with : for(var i = imgArray.length-1; i > 0; i--)

在函数nextImage()中用以下代码替换循环:for(var i = 0; i 0;我 - ) ;>