通過查看 的輸出console.log(document),我發現document具有以下屬性:onload=null;onloadstart=null;onloadend=null;onreadystatechange=null;我撰寫了以下代碼:
<html>
<head><title>test</title></head>
<body>
<script>
document.onload=function(){alert("document.onload");};
document.onloadstart=function(){alert("document.onloadstart");};
document.onloadend=function(){alert("document.onloadend");};
document.onreadystatechange=function(){alert("document.onreadystatechange");};
</script>
<div>hello</div>
</body>
</html>
有趣的是,document.onload,document.onloadstart,document.onloadend從來沒有被呼叫過,而document.onreadystatechange被呼叫了兩次,為什么?
uj5u.com熱心網友回復:
為什么不呼叫 document.onload?
首先,load事件(由瀏覽器創建)不會冒泡(因為它是這樣指定的):
document.body.onload = function(e) {
console.dir(e.bubbles)
}
因此,您只能load在它們發生的元素上監聽這些事件。
對于Document,沒有load列出將根據標準觸發的事件。
readystatechange另一方面,被列為可能發生的事件document。
但是,您可以肯定地在 上監聽load事件,document并且將呼叫事件回呼。但這只有在您手動觸發以下情況時才會發生document:
const event = new Event('load');
document.onload = function (e) {
console.log('load document')
}
document.dispatchEvent(event);
或者,如果您發出一個load在后代上冒泡的事件:
const event = new Event('load', {bubbles: true});
document.onload = function (e) {
console.log('load document')
}
document.body.dispatchEvent(event);
那么為什么onload那么會作為一個屬性出現呢?這是由于GlobalEventHandlersand Document includes GlobalEventHandlers),以及由于事件處理程式 IDL 屬性,將它們公開為on…事件屬性。
uj5u.com熱心網友回復:
我不確定,但試試這個:
window.addEventListener('load', () => {
alert("document.onload")
})
我只使用視窗 onl oad 事件,但如果我從未見過檔案 onl oad 事件,只需更改window為document.
就像我說的那樣,我不確定該怎么做,因為您顯示的代碼量要少。
uj5u.com熱心網友回復:
.onload是window物件的一部分,而不是document.
GlobalEventHandlers.onload
GlobalEventHandlers mixin 的 onl oad 屬性是一個事件處理程式,用于處理、和元素等
load上的事件。WindowXMLHttpRequest<iframe><img>
從我在 MDN 上看到.onloadstart并.onloadend用于影像等資源的情況來看,不知道它們是否可用于document/ window。GlobalEventHandlers.onloadstart
但我認為onreadystatechange你應該能夠模仿onloadstartand的行為onloadend。
Document.readyState
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/488791.html
標籤:javascript
