简体   繁体   English

JavaScript不会在页面加载时更改图像源

[英]Javascript does not change image source on page load

I'm very new to javascript. 我对javascript很陌生。 I'm trying to change the image source on page load. 我正在尝试在页面加载时更改图像源。 I don't know why this doesn't work. 我不知道为什么这行不通。 Could someone please provide me with some insight on it? 有人可以为我提供一些见解吗? Here's my html code: 这是我的html代码:

 <html> <body onload="changeImage()"> <ul id="character-list"> <li id="character1"> <img src="character1.jpg" width="250px" height="280px" alt="" /> </li> </ul> </body> <script> function changeImage(){ var charDiv = document.getElementById("character1"); var imgTag = charDiv.getElementsByTagName('img'); imgTag.src = "character2.jpg"; } </script> </html> 

getElementsByTagName("img") will give you an array of <img> elements. getElementsByTagName("img")将为您提供<img>元素数组。 In this case you need to simply access the only image element in that array charDiv.getElementsByTagName('img')[0] : 在这种情况下,您只需访问该数组charDiv.getElementsByTagName('img')[0]的唯一图像元素:

 <html> <body onload="changeImage()"> <ul id="character-list"> <li id="character1"> <img src="character1.jpg" width="250px" height="280px" alt="" /> </li> </ul> </body> <script> function changeImage(){ var charDiv = document.getElementById("character1"); var imgTag = charDiv.getElementsByTagName('img')[0]; imgTag.src = "character2.jpg"; } </script> </html> 

You can also use: 您还可以使用:

 function changeImage(){
      var imgTag = document.querySelector("#character1 img");

      imgTag.src = "new desired image path";
    }

changeImage();

Seems like simplest way, if you can't, for some reason, give an id to image . 似乎是最简单的方法, 如果由于某种原因而无法给image赋予ID

Demo: http://jsfiddle.net/ugw4q974/ 演示: http//jsfiddle.net/ugw4q974/

Why don't you use the same method to get the img as you do for the charDiv ? 为什么不使用与charDiv相同的方法来获取img? Just give your img an ID, and then simply access it by the ID. 只需为您的img一个ID,然后只需通过该ID即可对其进行访问。 Otherwise you will get back an array of all img -elements. 否则,您将获得所有img -elements的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM