jQuery-如何检查img src是否缺少文件名?

| 我有一个
<img>
 <img src=\"http://example.com/mmm/01.jpg\" class=\"test\">
如何检查src是否缺少
01.jpg
并将其替换为其他图像? 基本上
if (img src is \'http://example.com/mmm/\') { 
    replace src with \'http://example.com/mmm/test.jpg\'
}
    
已邀请:
这样的事情应该起作用:
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);
}
    
解决方案:jQuery / JavaScript替换损坏的图像 这不仅是堆栈溢出的第一击,也是Google的第一击...     
您可以检查src属性中的最后一个字符,以查看它是否是\'/ \'。
var img = $(\"img.test\");
var src = $(img).attr(\"src\");

if (src.lastIndexOf(\"/\")+1 == src.length){
    $(img).attr(\"src\",src+\"test.jpg\");
}
    
检查
$(\"img.test\").attr(\"src\")
    
$(yourImg).attr(\"src\")
将以字符串形式返回(或允许您设置)图片的网址,以便您可以将其与上述值进行比较。     
// 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\';
});
    

要回复问题请先登录注册