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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18867735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:39:17  来源:igfitidea点击:

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

javascriptjquery

提问by GibboK

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

我需要将srchtml 图像标记的相对 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
            });

回答by Anil kumar

Try like this

像这样尝试

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

回答by Moeri

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

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

回答by manish nautiyal

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

回答by Shakti Patel

used this code for src

将此代码用于 src

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

Demo

演示

回答by Code L?ver

Instead of below code:

而不是下面的代码:

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

Use this:

用这个:

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

回答by Arun P Johny

Your code can simplified a lot to

您的代码可以简化很多

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

回答by Steven Bakhtiari

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

Javascript 中的 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(...))

回答by Hossein Mehrzad

change image captcha refresh

更改图像验证码刷新

html:

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