通过HTML中的JS将图像的src分配给变量 [英] Assign src of image to a variable through JS in HTML

查看:114
本文介绍了通过HTML中的JS将图像的src分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过JS点击图片,将图像的src标签内容分配给变量:
Eg -

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
???

JS ???

我想将点击图像的图像源分配给变量,然后通过跨度在HTML上显示源。当我单击图像时,这一切都应该发生。并且要分配给变量的源应该是单击的图像。

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.

我该怎么办?

提前致谢。

推荐答案

尝试以下方法:

<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>

这篇关于通过HTML中的JS将图像的src分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆