当我调用“ showPrevious”函数时,当前变量值不会改变

时间:2019-05-28 15:05:05

标签: javascript html

该程序旨在更改图像元素的src属性      通过数组

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">

 <head>
 <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
 <title>Url next, previous</title>

 <script type="text/javascript">


 var imagesarr = ["Eikona1.jpg","Eikona2.jpg","Eikona3.jpg"];
 var current = 0;


 function showNext() {
     current ++;    

     if(current==imagesarr.length) {
        current = 0;
     }
     document.getElementById("img").src = imagesarr[current];   
   }

这是问题所在!它得到的价值:1 而不是-1。当前价格不起作用...通过调用showPrevious()函数,当前值应更改为-1的1。

  function showPrevious() {

    current = current - 1 ;  

     if(current < 0) {
        current = imagesarr.length - 1;
     }
     document.getElementById("img").scr = imagesarr[current];   
  }

 </script>


 </head>

 <body>

 <img src="Eikona1.jpg" id="img" alt="Einstein" style="width:600px; 
 height:500px"/>
 <br/>

点击事件将触发每个功能

 <input id="previous" type="button" value="Previous" style="width:220px; 
 margin-top:40px" onclick="showPrevious()"/>

 <input id="next" type="button" value="Next" style="width:220px; margin- 
 top:40px" onclick="showNext()"/> 

 </body>

 </html>

1 个答案:

答案 0 :(得分:0)

您有一个错字,src是scr,但此外还有逻辑问题。也许这个修订过的版本会清除它。

<script type="text/javascript">

var imagesarr = ["1","2","3"];
var current = 0;

function showNext() {
    current ++;

    if(current==imagesarr.length) {
       current = 0;
    }
    document.getElementById("img").src = imagesarr[current];
  }

 function showPrevious() {
   current --;

   if(current < 0) {
      current = imagesarr.length-1;
   }
   document.getElementById("img").src = imagesarr[current];
 }

</script>
相关问题