2011-04-21 76 views

回答

3

像這樣的東西應該工作:

var $img = jQuery("#myImg"); 
var src = $img.attr("src"); 

// if you have more image types, just add them to the regex. 
// I've used png and jpg as examples 
if(!/\.(jpg|png)$/.test(src)) { 

    var img = "test.jpg"; 

    // to see if the src url ends with/or not 
    if(!/\/$/.test(src)) { 
     img = "/" + img; 
    } 

    $img.attr("src", src + img); 
} 
0

檢查$("img.test").attr("src")

0

$(yourImg).attr("src")將返回(或允許您設置)的URL圖像作爲一個字符串,然後你可以將其與上面提到的值進行比較。

2

解決方案:jQuery/JavaScript to replace broken images

這是先打不只是在堆棧溢出,但在谷歌,以及...

+0

+1。在這篇文章中,這個評論是我認爲最好的解決方案:http://stackoverflow.com/questions/92720/jquery-javascript-to-replace-broken-images/#comments-168448 – 2011-04-21 16:46:05

1

您可以檢查src屬性中的最後一個字符,以查看它是否爲'/'或不...

var img = $("img.test"); 
var src = $(img).attr("src"); 

if (src.lastIndexOf("/")+1 == src.length){ 
    $(img).attr("src",src+"test.jpg"); 
} 
+0

這可能並不總是奏效。如果他沒有尾隨的'/'和沒有圖像怎麼辦?像'http:// www.google.com'? – 2011-04-21 16:46:34

0
// Can 'fix' many imgs at once (with the appropriate logic in the body) 
$('img').attr('src',function(i,src){ 
    // If it's a JPG, leave it alone, otherwise... 
    return /jpe?g$/.test(src) ? src : 'http://example.com/mmm/test.jpg'; 
});