Assign src of image to a variable through JS in HT

2019-09-06 20:07发布

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.

2条回答
男人必须洒脱
2楼-- · 2019-09-06 20:31

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>
查看更多
Bombasti
3楼-- · 2019-09-06 20:40

you can try this,

<img ng-src="{{myVar}}">
查看更多
登录 后发表回答