error

当一个资源加载失败或无法使用时,会在Element对象上触发error事件。例如当脚本执行错误、或图片无法找到或图片无效时。

Bubbles(支持冒泡) No
Cancelable(可撤销) No
Interface(接口) EventUIEvent
Event handler property(事件处理程序属性) onerror

如果事件对象是从用户界面元素生成的,则它是一个UIEvent实例;反之,它是一个Event实例。

示例

在线示例

HTML

<div class="controls">
  <button id="img-error" type="button">生成图像error</button>
  <img class="bad-img" />
</div>

<div class="event-log">
  <label>Event log:</label>
  <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea>
</div>

JS

const log = document.querySelector('.event-log-contents');

const badImg = document.querySelector('.bad-img');
badImg.addEventListener('error', (event) => {
    log.textContent = log.textContent + `${event.type}: Loading image\n`;
    console.log(event)
});

const imgError = document.querySelector('#img-error');
imgError.addEventListener('click', () => {
    badImg.setAttribute('src', 'i-dont-exist');
});

结果

规范

Specification Status
UI Events Working Draft

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
error eventChrome Full support YesEdge Full support ≤79Firefox Full support YesIE ? Opera ? Safari ? WebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android ? Safari iOS ? Samsung Internet Android Full support Yes

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown

参阅

  • This event on Window targets: error event