【问题标题】:Change image when clicking button单击按钮时更改图像
【发布时间】:2013-11-05 17:24:42
【问题描述】:

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

【问题讨论】:

标签: javascript image onclick


【解决方案1】:

你错过了.getElementById('theImage')中的引号

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

【讨论】:

    【解决方案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,不是变量,所以你必须把它放在引号里。

    【讨论】:

      【解决方案3】:

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

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

      Demo

      【讨论】:

        【解决方案4】:

        您可以使用内联 HTML&lt;img src="img1.jpg" onclick="this.src='img2.jpg'"&gt; 效果最好。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-04-14
          • 2017-01-21
          • 2012-01-21
          • 2012-10-07
          • 1970-01-01
          • 1970-01-01
          • 2013-07-24
          相关资源
          最近更新 更多