IMG SRC tags and JavaScript

前端 未结 13 1143
眼角桃花
眼角桃花 2020-12-02 02:09

Is it possible to call a JavaScript function from the IMG SRC tag to get an image url?

Like this:





        
相关标签:
13条回答
  • 2020-12-02 02:14

    Is it possible to call a JavaScript function from the IMG SRC tag to get an image url?

    Do you mean doing something like the following?

    <img src="javascript:GetImage()" />
    

    Unfortunately, no - you can't do that. However, you can do the following hack:

    function getImageUrl(img) {
       var imageSrc = "imageName/imagePath.jpg";
       if(img.src != imageSrc) { // don't get stuck in an endless loop
          img.src = imageSrc;
       }
    }
    

    Then, have the following html:

    <img src="http://yourdomain.com/images/empty.gif" onload="getImageUrl(this)" />
    

    The onload event will only fire if you have an actual image set to the src attribute - if you don't set that attribute or set it to an empty string or something similar, you will get no love. Set it to a single pixel transparent gif or something similar.

    Anyway, this hack works, but depending on what you are really trying to accomplish, this may not be the best solution. I don't know why you would want to do this, but maybe you have a good reason (that you would like to share with us!).

    0 讨论(0)
  • 2020-12-02 02:14

    OnLoad event of image called again and again do some thing like this

    0 讨论(0)
  • 2020-12-02 02:14

    Are you looking for this.src ?`

    <img src='images/test.jpg' onmouseover="alert(this.src);"> 
    
    0 讨论(0)
  • 2020-12-02 02:20

    You cannot do it inline the image @src, but you should be able to call it from an inline script block immediately following your image:

    <img src="" id="myImage"/>
    <script type="text/javascript">
      document.getElementById("myImage").src = GetImage();
    </script>
    
    0 讨论(0)
  • 2020-12-02 02:24

    I've had to do something like this before, and IIRC the trick winds up being that you can't change an src attribute of an image that's part of the DOM tree. So your best bet is to write your HTML skeleton without the image and 1)create an onLoad function that generates a new img element with document.createElement, 2) set the src attribute with setAttribute(), and 3) attach it to your DOM tree.

    0 讨论(0)
  • 2020-12-02 02:27

    Since you're using .NET, you could add the runat="server" attribute and set the src in your codebehind.

    0 讨论(0)
提交回复
热议问题