แอตทริบิวต์เหตุการณ์ onerror ใน HTML ถูกกระตุ้นเมื่อเกิดข้อผิดพลาดขณะโหลดไฟล์ภายนอกในเอกสาร HTML
ไวยากรณ์
<tagname onerror="script">เนื้อหา</tagname>
ตัวอย่าง
<!DOCTYPE html>
<html>
<head>
<style>
body { color: #000; height: 100vh; background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat; text-align: center; padding: 20px; }
.btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 40%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; }
</style>
</head>
<body>
<h1>ตัวอย่างแอตทริบิวต์เหตุการณ์ onerror ของ HTML</h1>
<button onclick="add()" class="btn">เพิ่มรูปธรรมชาติ</button>
<script>
function add() {
var imgEle = document.createElement('IMG');
imgEle.setAttribute("src", "nature.png");
imgEle.setAttribute("alt", "nature image");
imgEle.setAttribute("onerror", "errorFn()");
document.body.appendChild(imgEle);
}
function errorFn() {
document.body.style.background = "linear-gradient(45deg, #8BC6EC 0%, #9599E2 100%) no-repeat";
document.body.style.color = "#fff";
}
</script>
</body>
</html>
ผลลัพธ์
คลิกปุ่ม "เพิ่มรูปธรรมชาติ" เพื่อสร้างองค์ประกอบรูปภาพที่มี src ผิดและมี onerror แล้วเพิ่มเข้า body
เมื่อโหลดรูปไม่สำเร็จ จะกระตุ้น onerror เปลี่ยนพื้นหลังและสีตัวอักษร