How to efficiently change image attribute “src” from relative URL to absolute using jQuery?

后端 未结 8 719
旧巷少年郎
旧巷少年郎 2021-02-04 01:01

I need to change the src for an html image tag from relative to absolute url.

I am using the following code. urlRelative and urlAbsolute are created correct

相关标签:
8条回答
  • 2021-02-04 01:10

    The replace method in Javascript returns a value, and does not act upon the existing string object. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

    In your example, you will have to do

    $(this).attr("src", $(this).attr("src").replace(...))
    
    0 讨论(0)
  • 2021-02-04 01:15

    Instead of below code:

    $(this).attr("src").replace(urlRelative, urlAbsolute);
    

    Use this:

    $(this).attr("src",urlAbsolute);
    
    0 讨论(0)
  • 2021-02-04 01:18
    jQuery("#my_image").attr("src", "first.jpg")
    
    0 讨论(0)
  • 2021-02-04 01:21

    change image captcha refresh

    html:

     <img id="captcha_img" src="http://localhost/captcha.php" /> 
    

    jquery:

    $("#captcha_img").click(function()
        {
            var capt_rand=Math.floor((Math.random() * 9999) + 1);
            $("#captcha_img").attr("src","http://localhost/captcha.php?" + capt_rand);
        });
    
    0 讨论(0)
  • 2021-02-04 01:22

    Try $(this).attr("src", urlAbsolute);

    0 讨论(0)
  • 2021-02-04 01:22

    Your code can simplified a lot to

    $('img', resp).attr('src', function(idx, urlRelative ) {
        return self.config.proxy_server + self.config.location_images + urlRelative;
    });
    
    0 讨论(0)
提交回复
热议问题