简体   繁体   English

单击按钮时更改图像

[英]Change image when clicking button

This seems like it should work but doesn't. 这似乎应该起作用,但不起作用。 I'm not sure where the problem is - either I'm doing it wrong, or it's possible I have a syntax error. 我不确定问题出在哪里-我做错了,或者我可能有语法错误。 I just doesn't do anything. 我什么也没做。 I'm trying to get the current picture to change when the button is clicked. 我正在尝试单击按钮时更改当前图片。 I'm a beginner at Javascript, so please be gentle ;) Thank you! 我是Javascript的初学者,所以请保持柔和;)谢谢!

<html>
<script>
function pictureChange()
{
document.getElementById(theImage).src="http://31.media.tumblr.com/fca646cd8fe87906e605ad7e8d039903/tumblr_mmoz4fWT6U1soh1p8o1_500.png");
}
</script>
<body>
<img id="theImage" src="http://31.media.tumblr.com/18b5f8f0a00ad01e50f7ae2f513be52d/tumblr_msqcl4iwM01soh1p8o1_500.png">
<p><input type="button" id="theButton" value="click me!" onclick="pictureChange()"></p>
</body>
</html>

You missed the quotes in .getElementById('theImage') 您错过了.getElementById('theImage')的引号

 function pictureChange()
    {
    document.getElementById('theImage').src="http://31.media.tumblr.com/fca646cd8fe87906e605ad7e8d039903/tumblr_mmoz4fWT6U1soh1p8o1_500.png";
    }

Add " to getElementById argument and remove ) at the end of the line: 在行尾添加"getElementById参数并删除)

<script>
    function pictureChange()
    {
          document.getElementById("theImage").src="http://31.media.tumblr.com/fca646cd8fe87906e605ad7e8d039903/tumblr_mmoz4fWT6U1soh1p8o1_500.png";
    }
</script>

http://jsfiddle.net/cDd8J/ - here. http://jsfiddle.net/cDd8J/-此处。 It works. 有用。

theImage is just id of the element, not variable, so you have to put it in quotes. theImage只是元素的ID,而不是变量,因此您必须将其用引号引起来。

There are lot of ways you could try.Calling the function using inline attributes or calling it using the id in your script.Here's one , 您可以尝试多种方法。使用内联属性调用函数或使用脚本中的id调用函数。这里是一种,

theButton.onclick = function pictureChange()
{
   document.getElementById("theImage").src="http://31.media.tumblr.com/fca646cd8fe87906e605ad7e8d039903/tumblr_mmoz4fWT6U1soh1p8o1_500.png";
}

Demo 演示

您可以使用内联HTML<img src="img1.jpg" onclick="this.src='img2.jpg'">效果最佳。

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

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