jQuery - How to check if img src lacks filename?
I have a <img>
:
<img src="http://example.com/mmm/01.jpg" class="test">
How can I check if the src is missing the 01.jpg
and replace it with some other image?
Basically
if (img src is 'http://example.com/mmm/') { 开发者_高级运维
replace src with 'http://example.com/mmm/test.jpg'
}
Something like this should work:
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);
}
Solution: jQuery/JavaScript to replace broken images
This is the first hit not just on stack overflow, but on google as well...
You can check the last character in the src attribute to see if it's a '/' or not...
var img = $("img.test");
var src = $(img).attr("src");
if (src.lastIndexOf("/")+1 == src.length){
$(img).attr("src",src+"test.jpg");
}
Check $("img.test").attr("src")
$(yourImg).attr("src")
will return you (or allow you to set) the url for the image as a string so you can then compare it with the values mentioned above.
// 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';
});
精彩评论