简体   繁体   English

如何使用jQuery有效地将图像属性“src”从相对URL更改为绝对?

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

I need to change the src for an html image tag from relative to absolute url. 我需要将html图像标记的src从相对URL更改为绝对URL。

I am using the following code. 我使用以下代码。 urlRelative and urlAbsolute are created correctly but I cannot modify the image in the last line. urlRelative和urlAbsolute是正确创建的,但我无法在最后一行修改图像。

What could be wrong wrong in my script? 我的剧本中有什么错误?

..... // other code here

     request.done(function(resp) {
            var imgTags = $('img', resp).each(function() {
                var urlRelative = $(this).attr("src");
                var urlAbsolute = self.config.proxy_server + self.config.location_images + urlRelative;
                $(this).attr("src").replace(urlRelative, urlAbsolute); // problem here
            });

试试这样吧

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

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

jQuery("#my_image").attr("src", "first.jpg")

used this code for src 将此代码用于src

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

Demo 演示

Your code can simplified a lot to 您的代码可以简化很多

$('img', resp).attr('src', function(idx, urlRelative ) {
    return self.config.proxy_server + self.config.location_images + urlRelative;
});

Instead of below code: 而不是下面的代码:

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

Use this: 用这个:

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

The replace method in Javascript returns a value, and does not act upon the existing string object. Javascript中的replace方法返回一个值,并且不对现有的字符串对象起作用。 See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace 请参阅: 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(...))

change image captcha refresh 更改图像验证码刷新

html: HTML:

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

jquery: jQuery的:

$("#captcha_img").click(function()
    {
        var capt_rand=Math.floor((Math.random() * 9999) + 1);
        $("#captcha_img").attr("src","http://localhost/captcha.php?" + capt_rand);
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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