简体   繁体   English

使用javascript更改图像的src

[英]Changing the src of an image with javascript

I have been trying to use the following piece of code to change the src of an image 我一直在尝试使用以下代码来更改图像的src

document.getElementById('test').src='images/test2.png';

My code looks like this. 我的代码如下所示。 There's some CSS and other things in there but the important parts are the div and the img, and the function. 里面有一些CSS和其他内容,但是重要的部分是div和img以及函数。

<div id='splashScreen' class='splash'>
  <button class='bigButton' onclick='introSplash()'>Hi</button>
  <img class='splashImages' src='images/splashScreen1.png'>
</div>

this is my image with a page-sized transparent button over the top of it 这是我的图像,顶部有一个页面大小的透明按钮

<script>
function introSplash() {
    document.getElementById('splashImages').src='images/splashScreen2.png';
  }
</script>

this function should be replacing the image under the button. 此功能应替换按钮下的图像。

Pressing the button with this code returns the following error message: 按此代码的按钮将返回以下错误消息:

Uncaught TypeError: Cannot set property 'src' of null at introSplash 未被捕获的TypeError:无法在introSplash上​​将属性'src'设置为null

all of the images are locally saved and exist with those names 所有图像都保存在本地并与这些名称一起存在

I'm not sure why this is occurring, and would appreciate any help. 我不确定为什么会发生这种情况,将不胜感激。

You need to add the ID test to the <img> element: 您需要将ID test添加到<img>元素:

<img id='test' class='splashImages' src='images/splashScreen1.png' />

Now your code will work. 现在您的代码可以使用了。

The alternative, without adding any IDs, would be to use document.getElementsByClassName like so: 另一种选择是不添加任何ID,而是使用document.getElementsByClassName如下所示:

document.getElementsByClassName('splashImages')[0].src='images/test2.png';

Please verify you are using document.getElementById('splashImages') but the html element has not ID. 请确认您使用的是document.getElementById('splashImages')但html元素没有ID。 Add the id attribute 添加id属性

<img id="splashImages" class='splashImages' src='images/splashScreen1.png'>

Please try this and let me know how it works :) 请尝试一下,让我知道它是如何工作的:)

您尝试通过id获取元素,但仅给出class="splashImages"

document.getElementById('splashImages') returns null because the element you want does not have the correct id. document.getElementById('splashImages')返回null因为所需的元素没有正确的ID。 Use getElementsByClassName instead, or give it the correct id. 请改用getElementsByClassName ,或为其提供正确的ID。

So you should implement one of following changes: 因此,您应该实施以下更改之一:

<script>
function introSplash() {
    document.getElementsByClassName('splashImages').src='images/splashScreen2.png';
  }
</script>

or 要么

<div id='splashScreen' class='splash'>
  <button class='bigButton' onclick='introSplash()'>Hi</button>
  <img id='splashImages' class='splashImages' src='images/splashScreen1.png'>
</div>

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

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