error
当一个资源加载失败或无法使用时,会在Element
对象上触发error
事件。例如当脚本执行错误、或图片无法找到或图片无效时。
示例
在线示例
HTML
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
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 |
---|
UI Events # event-type-error |
浏览器兼容性
BCD tables only load in the browser
参阅
- This event on
Window
targets:error
event