Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Thuộc tính sự kiện onerror trong HTML

Thuộc tính sự kiện onerror trong HTML được kích hoạt khi xảy ra lỗi trong khi tải một tệp tin bên ngoài (external file) trong tài liệu HTML.

Cú pháp

Cú pháp như sau:

<tagname onerror="script">Nội dung</tagname>

Ví dụ

Dưới đây là ví dụ minh họa thuộc tính sự kiện onerror trong HTML:

<!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>Demo thuộc tính sự kiện onerror trong HTML</h1>
<button onclick="add()" class="btn">Thêm hình ảnh thiên nhiên</button>
<script>
  function add() {
    var imgEle = document.createElement('IMG');
    imgEle.setAttribute("src", "nature.png");
    imgEle.setAttribute("alt", "hình ảnh thiên nhiên");
    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>

Kết quả

Thuộc tính sự kiện onerror trong HTML

Nhấn vào nút "Thêm hình ảnh thiên nhiên" để tạo một phần tử hình ảnh với thuộc tính src sai và thuộc tính onerror, sau đó thêm vào body.

Thuộc tính sự kiện onerror trong HTML