在 Javascript 中更改和循环显示图像 onclick

Change and cycle through images onclick in Javascript

我只是想循环浏览所有图像,最后通过 onclick 函数不执行任何操作。但是我遇到了麻烦。任何建议都会很棒。

<SCRIPT>

var quizImagesB = new Array(); 

 quizImagesB[0]="images/dratiniB.png"
 quizImagesB[1]="images/parasB.png"
 quizImagesB[2]="images/mewB.png"
 quizImagesB[3]="images/doduoB.png"
 quizImagesB[4]="images/meowthB.png"
 quizImagesB[5]="images/cloysterB.png"
 quizImagesB[6]="images/ponytaB.png"
 quizImagesB[7]="images/articunoB.png"
 quizImagesB[8]="images/flareonB.png"

function updateImgB(){
for(var i=0; quizImagesB<.length; i++){
var url = 'url(' + quizImagesB[i] + ')';    //alters css
document.getElementById('pkmnImg').style.backgroundImage=url;
 }
}

</SCRIPT>

<style type="text/css">
#pkmnImg
{
background-image: url(images/charmanderB.png);
background-repeat: no-repeat;
text-align: center;
width: 400px;
height: 450px;
margin-top: 10px;
margin-left: 15px;
}</style>

<FORM>
 <INPUT TYPE="Button" VALUE="Change the image source" onClick="updateImgB();">
</FORM>

<div id ="pkmnImg"></div>

好的,这应该可以。您不想循环遍历数组,而是希望在每次单击时将 i 的值增加 1,从而允许您以这种方式循环遍历数组 - 请参阅 jsfiddle - https://jsfiddle.net/ffd7tmwy/1/

Javascript:

    var quizImagesB = new Array(); 

     quizImagesB[0]="images/dratiniB.png"
     quizImagesB[1]="images/parasB.png"
     quizImagesB[2]="images/mewB.png"
     quizImagesB[3]="images/doduoB.png"
     quizImagesB[4]="images/meowthB.png"
     quizImagesB[5]="images/cloysterB.png"
     quizImagesB[6]="images/ponytaB.png"
     quizImagesB[7]="images/articunoB.png"
     quizImagesB[8]="images/flareonB.png"

     var i = 0
     function updateImgB(){
        var i = i + 1;
        var url = 'url(' + quizImagesB[i] + ')';
        document.getElementById('pkmnImg').style.backgroundImage=url;
      }

HTML

<div id='pkmnImg'></div>
<form>
    <input type="button" value="Change the image source" onClick="updateImgB()">
</form>