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

我需要将html图像标记的src从相对URL更改为绝对URL。

我使用以下代码。 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 }); 

试试这样吧

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

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

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

将此代码用于src

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

演示

而不是下面的代码:

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

用这个:

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

您的代码可以简化很多

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

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

在您的示例中,您将不得不这样做

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

更改图像validation码刷新

HTML:

   

jQuery的:

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