javascript 单击按钮时更改图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19609387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change image when clicking button
提问by user2884447
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>
回答by Roar
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";
}
回答by Crazy Yoghurt
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. It works.
http://jsfiddle.net/cDd8J/- 这里。有用。
theImage
is just id of the element, not variable, so you have to put it in quotes.
theImage
只是元素的 id,而不是变量,所以你必须把它放在引号中。
回答by Md. Ashaduzzaman
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";
}
回答by CoderKube
You can use inline HTML:
<img src="img1.jpg" onclick="this.src='img2.jpg'">
works best.
您可以使用内联 HTML:
<img src="img1.jpg" onclick="this.src='img2.jpg'">
效果最好。