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

时间:2013-09-18 08:50:21

标签: javascript jquery

我需要将html图片代码的src从相对网址更改为绝对网址。

我正在使用以下代码。 urlRelative和urlAbsolute是正确创建的,但我无法在最后一行修改图像。

我的剧本中有什么错误?

..... // 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
            });

8 个答案:

答案 0 :(得分:61)

试试这个

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

答案 1 :(得分:3)

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

答案 2 :(得分:3)

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

答案 3 :(得分:2)

将此代码用于src

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

Demo

答案 4 :(得分:1)

您的代码可以简化为

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

答案 5 :(得分:1)

而不是代码:

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

使用此:

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

答案 6 :(得分:0)

Javascript中的replace方法返回一个值,并且不对现有的字符串对象起作用。请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

在您的示例中,您必须执行

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

答案 7 :(得分:0)

更改图片验证码刷新

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);
    });