JavaScript 有個事件叫做 onerror,是說我也是今天才知道,可以用在當你圖片沒抓到時,出現叉燒包及 server responded status 403,可以做一些事情。
通常在網路上爬到的範例,都是將 onerror 的事件偵測寫在行內,像下面這一行這樣,
以這個例子來說,當 demo.jpg 找不到時,就會去做寫在 onerror 裡面的事情,當然啦,假如有 demo.jpg,應該不會觸發 onerror 事件。
<img src="demo.jpg" onerror="alert('no image');"/>
那麼像我不習慣把事件綁在 HTML tag 上,
所以用 jQuery 的事件綁定 (bind) 來做:
當抓到 error 時,把該 img 標籤的 src 取代成預設的圖片。
有趣的是,上面的做法只適合非 Ajax 產生的 img ,我只有第一次載入畫面的時候,會做這件事情,當我點按是用 ajax 處理的分頁時,這下 high 了, 怎麼處理呢?
這時候想到 jQuery 有個 ajaxStop,可以偵測到當你切換頁面,也就是透過 ajax 切換畫面時且在 AJAX 請求結束後執行ajaxStop() 。
真有趣 :)
參考網址:
通常在網路上爬到的範例,都是將 onerror 的事件偵測寫在行內,像下面這一行這樣,
以這個例子來說,當 demo.jpg 找不到時,就會去做寫在 onerror 裡面的事情,當然啦,假如有 demo.jpg,應該不會觸發 onerror 事件。
<img src="demo.jpg" onerror="alert('no image');"/>
那麼像我不習慣把事件綁在 HTML tag 上,
所以用 jQuery 的事件綁定 (bind) 來做:
當抓到 error 時,把該 img 標籤的 src 取代成預設的圖片。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function () { | |
$('img').bind('load readystatechage error', function (e) { | |
//綁定 load, readystatechage error三個事件, | |
//不過只有error在這裡會用到 :P | |
var e = e.type; | |
switch(e){ | |
case 'error': | |
console.log('抓不到圖'); | |
$(this).attr('src','/images/no_img.png'); | |
break; | |
} | |
}); | |
}); |
有趣的是,上面的做法只適合非 Ajax 產生的 img ,我只有第一次載入畫面的時候,會做這件事情,當我點按是用 ajax 處理的分頁時,這下 high 了, 怎麼處理呢?
這時候想到 jQuery 有個 ajaxStop,可以偵測到當你切換頁面,也就是透過 ajax 切換畫面時且在 AJAX 請求結束後執行ajaxStop() 。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function detect_if_image_loaded(){ | |
$('img').bind('error', function (e) { | |
var e = e.type; | |
switch(e){ | |
case 'error': | |
$(this).attr('src','/images/no_img.png'); | |
break; | |
} | |
}); | |
} | |
//第一次載入的時候不是ajax,所以先叫一次 | |
detect_if_image_loaded(); | |
$(document).ajaxStop(function() { | |
detect_if_image_loaded(); | |
}); |
參考網址:
沒有留言:
張貼留言
若你看的文章,時間太久遠的問題就別問了,因為我應該也忘了... XD