图片不存在就显示默认图片

有些时候我们需要批量显示数据库中的图片,数据库中保存的当然是图片的路径。但是如果发现某些图片不存在,网页上的红叉会显得很难看,这时候我们可以选择显示默认图片来代替,这样会显得非常有人性化。

利用 image 对象的 onerror 事件来判断,出错则更换 image 对象的 src 为默认图片的 URL。

<img src="http://www.nowamagic.net/images/new_logo.png" onerror="javascript:this.src='http://www.nowamagic.net/images/logo.gif' "  />  

JavaScript onerror 事件

使用 onerror 事件是一种老式的标准的在网页中捕获 Javascript 错误的方法。

只要页面中出现脚本错误,就会产生 onerror 事件。如果需要利用 onerror 事件,就必须创建一个处理错误的函数。你可以把这个函数叫作 onerror 事件处理器 (onerror event handler)。这个事件处理器使用三个参数来调用:msg(错误消息)、url(发生错误的页面的 url)、line(发生错误的代码行)。

onerror=handleErrfunction handleErr(msg,url,l)
{
	//Handle the error here
	return true or false
}

浏览器是否显示标准的错误消息,取决于 onerror 的返回值。如果返回值为 false,则在控制台 (JavaScript console) 中显示错误消息。反之则不会。

下面的例子展示如何使用 onerror 事件来捕获错误:

<html>
<head>
<script type="text/javascript">
onerror=handleErr
var txt=""
function handleErr(msg,url,l)
{
	txt="There was an error on this page.nn"
	txt+="Error: " + msg + "n"
	txt+="URL: " + url + "n"
	txt+="Line: " + l + "nn"
	txt+="Click OK to continue.nn"
	alert(txt)
	return true
}
function message()
{
	adddlert("Welcome guest!")
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>

posted on 2014-12-02 19:48  复活的老羊  阅读(166)  评论(0编辑  收藏  举报

导航