簡體   English   中英

如何使用jQuery有效地將圖像屬性“src”從相對URL更改為絕對?

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

我需要將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);

演示

您的代碼可以簡化很多

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

而不是下面的代碼:

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

用這個:

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

Javascript中的replace方法返回一個值,並且不對現有的字符串對象起作用。 請參閱: https//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

在您的示例中,您將不得不這樣做

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

更改圖像驗證碼刷新

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM