在使用PhoneGap时,它有一些使用文档的默认JavaScript代码。addEventListener,但我有自己的代码,使用window。addEventListener
function onBodyLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("touchmove", preventBehavior, false);
window.addEventListener('shake', shakeEventDidOccur, false);
}
有什么区别,用哪个更好?
文档和窗口是不同的对象,它们有一些不同的事件。在它们上使用addEventListener()监听指向不同对象的事件。您应该使用实际有您感兴趣的事件的那个。
例如,在窗口对象上有一个“调整大小”事件,而不是在文档对象上。
例如,“readystatechange”事件只在文档对象上。
因此,基本上,您需要知道哪个对象接收您感兴趣的事件,并在该特定对象上使用. addeventlistener()。
下面是一个有趣的图表,显示了哪种类型的对象创建哪种类型的事件:https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference
If you are listening to a propagated event (such as the click event), then you can listen for that event on either the document object or the window object. The only main difference for propagated events is in timing. The event will hit the document object before the window object since it occurs first in the hierarchy, but that difference is usually immaterial so you can pick either. I find it generally better to pick the closest object to the source of the event that meets your needs when handling propagated events. That would suggest that you pick document over window when either will work. But, I'd often move even closer to the source and use document.body or even some closer common parent in the document (if possible).
文档和窗口是不同的对象,它们有一些不同的事件。在它们上使用addEventListener()监听指向不同对象的事件。您应该使用实际有您感兴趣的事件的那个。
例如,在窗口对象上有一个“调整大小”事件,而不是在文档对象上。
例如,“readystatechange”事件只在文档对象上。
因此,基本上,您需要知道哪个对象接收您感兴趣的事件,并在该特定对象上使用. addeventlistener()。
下面是一个有趣的图表,显示了哪种类型的对象创建哪种类型的事件:https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference
If you are listening to a propagated event (such as the click event), then you can listen for that event on either the document object or the window object. The only main difference for propagated events is in timing. The event will hit the document object before the window object since it occurs first in the hierarchy, but that difference is usually immaterial so you can pick either. I find it generally better to pick the closest object to the source of the event that meets your needs when handling propagated events. That would suggest that you pick document over window when either will work. But, I'd often move even closer to the source and use document.body or even some closer common parent in the document (if possible).
窗口绑定引用浏览器提供的内置对象。它表示包含文档的浏览器窗口。调用它的addEventListener方法注册第二个参数(回调函数),以便在它的第一个参数描述的事件发生时调用。
<p>Some paragraph.</p>
<script>
window.addEventListener("click", () => {
console.log("Test");
});
</script>
在选择窗口或文档到addEventListners之前应该注意以下几点
大多数事件是相同的窗口或文件,但
一些事件,如调整大小和其他与加载相关的事件,
卸载、开/关均应设置在窗户上。
既然窗口中有文档,那么使用文档to是一个很好的做法
处理(如果它可以处理),因为事件将首先击中文档。
上注册的许多事件无法响应
窗口,因此您将需要使用文档来注册事件。