2015-12-26 26 views
0

我想单击按钮时更改图像。以下是我的代码,但它不起作用。请帮助我。以HTML格式提交时更改图像

<!DOCTYPE html> 

<html lang="en"> 
    <head> 
     <meta charset="utf-8" /> 
     <title>Image</title> 

    </head> 
    <body> 
     <h1>My Image</h1> 
<p> 
     <img src="C:\Users\Hrushikesh\Pictures\iCloud Photos\Downloads\2015\IMG_3695.jpg" alt="HTML5 Icon" style="width:256px;height:256px;"> 
</p> 
     <button onclick="picturechange()"><img src="C:\Users\Hrushikesh\Desktop\star2.jpg" alt="HTML5 Icon" style="width:16px;height:16px;" id="pic1"></button> 
     <script> 
      function picturechange() 
      { 
       document.getElementById("pic1").src="C:\Users\Hrushikesh\Desktop\star1.jpg"; 
      } 
     </script> 
    </body> 
</html> 
+2

欢迎堆栈溢出,请务必检查出[**怎么问好问题**](http://stackoverflow.com/help/how-to-ask)。您的问题与主题无关,因为您需要调试帮助([*参见主题问题*](http://stackoverflow.com/help/on-topic))。另外请确保生成一个可重复的例子,提供一个小提琴的片段可以实现这一点。 –

+1

参考SO上的类似问题http://stackoverflow.com/questions/7462119/dynamically-replace-img-src-attribute-with-jquery – pratikpawar

回答

0

您的图片可能不被显示出来,由于以下原因

  • 你需要加载任何地方资源与完整路径前添加前缀file:///
  • 如果您正在通过Web服务器运行您的网页,则可能在您的浏览器中收到错误''不允许加载本地资源'。
+0

谢谢Ahsan,代码工作后添加文件:/// – Hrushikesh

+0

请考虑投票我的答案...谢谢... – Ahsan

1

此代码应该很好地工作,将其更改为自己的喜好: - ]

window.picturechange = function() { 
 
\t document.getElementById("pic").src = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/84/Example.svg/120px-Example.svg.png"; 
 
};
<p> 
 
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Example.jpg/116px-Example.jpg" alt="HTML5 Icon" style="width:256px;height:256px;" id="pic"> 
 
</p> 
 
<button onclick="picturechange()">Click Me</button>