日期:2014-05-16  浏览次数:20437 次

谁会JS 帮个忙
<img src ="....." onerror="this.src='images/error.jpg';"/>  
 这是普通的图片如果不存在用另外一张图片代替  
 怎么样写个JS 判断页面内所有的图片 是否存在 
 不存在的图片 就用默认的图片代替?

------解决方案--------------------
多个时可以这样!

L@_@K
HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title> new document </title>
    <meta name="generator" content="editplus" />
    <meta name="author" content="Gao YiXiang" />
    <meta name="email" content="yixianggao@126.com" />
    <meta name="keywords" content="javascript dhtml dom" />
    <meta name="description" content="I love web development." />
</head>
<body>
    <img src="http://www.csdn.net/Images/logo_csdn.111" />
    <img src="http://www.csdn.net/Images/logo_csdn.222" />
    <img src="http://www.csdn.net/Images/logo_csdn.333" />
    <script type="text/javascript">
    <!--
var oImgs = document.getElementsByTagName("img");
for (var i=0; i<oImgs.length; i++)
{
    oImgs[i].onerror = function()
    {
        this.src='http://www.csdn.net/Images/logo_csdn.gif';
    };
}
    //-->
    </script>
</body>
</html>

------解决方案--------------------
function init()
{
var errorImgUrl = 'images/error.jpg';
var imgs= document.getElementsByTagName("img");
for(var i=0;i<imgs.length;i++)
{
imgs[i].onerror = function()
{
this.src=errorImgUrl;
}
}
}

html body标签中添加 
<body onload='init()'>
<yourHtmlCode>
</yourHtmlCode>
</body>