2011-04-21 48 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'; 
});