单击按钮时更改图像

时间:2013-10-26 17:01:51

标签: javascript image onclick

这似乎应该有效,但不是。我不确定问题出在哪里 - 我做错了,或者我可能有语法错误。我什么都没做。我试图在点击按钮时改变当前图片。我是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>

4 个答案:

答案 0 :(得分:4)

您错过了.getElementById('theImage')

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

答案 1 :(得分:2)

"添加到getElementById参数,并删除该行末尾的)

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

http://jsfiddle.net/cDd8J/ - 这里。它有效。

theImage只是元素的id,而不是变量,所以你必须把它放在引号中。

答案 2 :(得分:0)

你可以尝试很多方法。使用内联属性调用函数或使用脚本中的id调用它。这是一个,

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

Demo

答案 3 :(得分:0)

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

相关问题