--- title: error slug: Web/API/Element/error_event translation_of: Web/API/Element/error_event original_slug: Web/Events/error ---
当一个资源加载失败或无法使用时,会在{{domxref("Element")}}对象上触发error
事件。例如当脚本执行错误、或图片无法找到或图片无效时。
Bubbles(支持冒泡) | No |
---|---|
Cancelable(可撤销) | No |
Interface(接口) | {{domxref("Event")}} 或{{domxref("UIEvent")}} |
Event handler property(事件处理程序属性) | {{domxref("GlobalEventHandlers/onerror", "onerror")}} |
如果事件对象是从用户界面元素生成的,则它是一个{{domxref("UIEvent")}}实例;反之,它是一个{{domxref("Event")}}实例。
<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>
body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } button { height: 2rem; margin: .5rem; } img { width: 0; height: 0; }
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'); });
{{ EmbedLiveSample('Live_example', '100%', '150px') }}
Specification | Status |
---|---|
{{SpecName('UI Events', '#event-type-error')}} | {{Spec2('UI Events')}} |
{{Compat("api.Element.error_event")}}
Window
targets: {{domxref("Window/error_event", "error")}} event