例子:
<!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></title> <script src="Js/jquery-1.9.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { ImageLoadEx(); }); function ImageLoadEx() { //加載不到 圖片 時顯示 默認圖片 $('img').error(function () { //加載圖片 出現404狀態時觸發 $(this).attr("src", "Image/default.jpg"); //將加載不到的圖片 的src屬性 修改成默認 圖片 ,注意:默認圖片必須保證存在,否則 會一直 調用 此函數 }); } </script> </head> <body> <img src="Image/ad2.png" /> <div> <div> <img src="ad2.png" /></div> </div> </body> </html>
注意:ImageLoadEx() 必須在瀏覽器渲染 img HTML標簽 完成 之后執行,如果 img 標簽是用js動態添加的 請在添加完成后 重新調用一下ImageLoadEx()函數