--- title: 'Window: error event' slug: Web/API/Window/error_event translation_of: Web/API/Window/error_event ---
当资源加载失败或无法使用时,会在{{domxref("Window")}}对象触发error
事件。例如:script 执行时报错。
Bubbles(支持冒泡) | No |
---|---|
Cancelable(可撤销) | No |
Interface(接口) | {{domxref("Event")}} or {{domxref("UIEvent")}} |
Event handler property(事件处理程序属性) | onerror |
如果它是由用户界面元素生成的,或者是由事件实例生成的,那么此事件是{{domxref("UIEvent")}}实例。
<div class="controls"> <button id="script-error" type="button">Generate script 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'); window.addEventListener('error', (event) => { log.textContent = log.textContent + `${event.type}: ${event.message}\n`; console.log(event) }); const scriptError = document.querySelector('#script-error'); scriptError.addEventListener('click', () => { const badCode = 'const s;'; eval(badCode); });
{{ EmbedLiveSample('Live_example', '100%', '150px') }}
Specification | Status |
---|---|
{{SpecName('UI Events', '#event-type-error')}} | {{Spec2('UI Events')}} |
{{Compat("api.Window.error_event")}}
Element
targets: error
event