Assign src of image to a variable through JS in HTML

老子叫甜甜 提交于 2019-12-25 04:30:14

问题


I want to assign content of the src tag of image to a variable on clicking on the image through JS: Eg-

HTML

<div id="img">
<img src="image1.jpg">
<img src="image2.jpg">
</div>
<span id="source"/>

JS ???

I want to assign the image source of the clicked image to a variable and then display the source on HTML through span. This all should happen when I click the image. And the source that is going to be assigned to variable should be of the clicked image.

How can I do it?

Thanks in advance.


回答1:


try the following:

<html>
  <head>

  <script>
      function setImage(id){
         var element = document.getElementById(id).src;
         document.getElementById("source").innerHTML = "<img src='" +   element + "' />";
      }

  </script>

  </head>

  <body>
         <div id="img">
           <img id="img1" src="image1.jpg" onclick="setImage(this.id)" >
           <img id="img2" src="image2.jpg" onclick="setImage(this.id)" >
         </div>
        <span id="source"></span>
   </body>
  </html>



回答2:


you can try this,

<img ng-src="{{myVar}}">


来源:https://stackoverflow.com/questions/42675989/assign-src-of-image-to-a-variable-through-js-in-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!