简体   繁体   中英

How can i return img.src by clicking on an image with javascript?

I am trying to create a function with javascript where a user upon clicking on an image can retrieve that images src as a URL. I am very new to javascript and my attempts so far at creating a function activated by "onclick" of an image are:

var showsrc = function(imageurl)
var img = new Image();
img.src = imageurl
return img.src

to call the results i have been trying to insert the image.src into my html using

document.getElementById("x").innerHTML=imageurl; 

Im having very little success. Any help would be greatly appreciated. Thank you.

I tested this in IE9 and Chrome 17. Add an onclick handler to the body (or nearest container for all your images) and then monitor if the clicked element is an image. If so show the url.

http://jsfiddle.net/JbHdP/

var body = document.getElementsByTagName('body')[0];
body.onclick = function(e) {
    if (e.srcElement.tagName == 'IMG')    alert(e.srcElement.src);  
};​

I think you want something like this: http://jsfiddle.net/dLAkL/

See code here:

HTML:

<div id="urldiv">KEINE URL</div>
<div>
    <img src="http://www.scstattegg.at/images/netz-auge.jpg" onclick="picurl(this);">
    <img src="http://www.pictokon.net/bilder/2007-06-g/sonnenhut-bestimmung-pflege-bilder.jpg.jpg" onclick="picurl(this);">
</div>​

JAVASCRIPT

picurl = function(imgtag) {
    document.getElementById("urldiv").innerHTML = imgtag.getAttribute("src");
}​

Image tags do not have an 'innerHTML', since they're singleton tags - they cannot have any children. If your x id is the image tag itself, then:

 alert(document.getElementById('x').src);

would spit out the src of the image.

Here's a naïve solution with just javascript (probably not cross-browser compatible):

<!doctype html>
<html>
  <head>
    <script>
      function init() {
        var images = document.getElementsByTagName('img');

        for(var i = 0, len = images.length; i < len; i++) {
          images[i].addEventListener('click', showImageSrc);
        }
      }

      function showImageSrc(e) {
        alert(e.target.src);
      }
    </script>
  </head>
  <body onload="init()">
    <img src="http://placekitten.com/300/300">
  </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM