图片正在加载为空

我是Java语言的新手,但我尝试使用onload()设置默认图像,但我认为它无法达到我在数组中设置的图像,因此我不知道为什么。


单击按钮后,我将使它旋转图像,但是我什至无法获得要添加的默认图像。


var images = ['img/profile.jpg', 'img/mountain.jpg', 'img/sanfran.jpg'];

var num=1;


function loadPage()

{

    document.getElementById("pictures").src = images[0].src;

}


function nextImage(pictures)

{

    var img = document.getElementById("pictures");

    document.getElementById("pictures").src = images[1].src;

    console.log(num++); // I have this just to make sure that it is catching something

}


<div id="maincontent">

  <div id="pictures">

     <img src="img/mountain.jpg">

  </div>

  <div id="paragraph">

    <p>

    </p>

    <button onclick="nextImage()">Switch Images</button>

  </div>

</div>


UYOU
浏览 158回答 3
3回答

Smart猫小萌

这里的图像是一个javascript数组。因此,您不能使用.src,因为它不是HTML img元素var images = ['img/profile.jpg', 'img/mountain.jpg', 'img/sanfran.jpg'];var num=1;//This function will run on body onloadfunction loadPage(){&nbsp; &nbsp; document.getElementById("pictures").src = images[0];}//This function will run on button clickfunction nextImage(){&nbsp; &nbsp; var img = document.getElementById("pictures");&nbsp; &nbsp; document.getElementById("pictures").src = images[1];&nbsp; &nbsp; console.log(num++); // I have this just to make sure that it is catching something}<body onload="loadPage()">&nbsp; &nbsp; <div id="maincontent">&nbsp; &nbsp; &nbsp; &nbsp; <img id="pictures" src="img/mountain.jpg">&nbsp; &nbsp; &nbsp; &nbsp; <div id="paragraph">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button onclick="nextImage()">Switch Images</button>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div></body>

湖上湖

试试这个:<script>var images = ['img/profile.jpg', 'img/mountain.jpg', 'img/sanfran.jpg'];var num=0;function loadPage(){&nbsp; &nbsp; document.getElementById("pictures").src = images[0].src;}function nextImage(pictures){&nbsp; &nbsp; if(num<images.length-1) {&nbsp; &nbsp; &nbsp; &nbsp; num = num+1;&nbsp; &nbsp; } else {&nbsp; &nbsp; num = 0;&nbsp; &nbsp; }&nbsp; &nbsp; var img = document.getElementById("pictures");&nbsp; &nbsp; document.getElementById("pictures").src = images[num];&nbsp; &nbsp; console.log(num); // I have this just to make sure that it is catching something}</script><div onload="loadPage()">&nbsp; <div id="imageholder">&nbsp; &nbsp; &nbsp;<img id="pictures" src="img/mountain.jpg">&nbsp; </div>&nbsp; <div id="paragraph">&nbsp; &nbsp; <p>&nbsp; &nbsp; </p>&nbsp; &nbsp; <button onclick="nextImage()">Switch Images</button>&nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript