document.addEventListener和window.addEventListener之间的区别? [英] Difference between document.addEventListener and window.addEventListener?
问题描述
在使用PhoneGap时,它有一些使用 document.addEventListener
的默认JavaScript代码,但是我有自己的代码,使用 window.addEventListener
:
function onBodyLoad(){
文档。 addEventListener(deviceready,onDeviceReady,false);
document.addEventListener(touchmove,preventBehavior,false);
window.addEventListener('shake',shakeEventDidOccur,false);
}
有什么区别,哪个更好使用?
文档
和窗口
是不同的对象,它们有一些不同的事件。在它们上使用 addEventListener()
侦听发往不同对象的事件。你应该使用一个实际上有你感兴趣的事件。
例如,有一个 例如, 所以基本上,你需要知道哪个对象收到你感兴趣的事件,并使用 这是一个有趣的图表,显示了哪些类型的对象创建了哪些类型的事件: https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference 如果您正在侦听传播的事件(例如click事件),则可以在文档对象或窗口对象上侦听该事件。传播事件的唯一主要区别在于时间安排。事件将在 While using PhoneGap, it has some default JavaScript code that uses What is the difference and which is better to use? The For example, there is a For example, the So basically, you need to know which object receives the event you are interested in and use Here's an interesting chart that shows which types of objects create which types of events: 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.addEventListener和window.addEventListener之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!resize$ c $ c code code code code code code code
DOMContentLoaded
事件只在文档
对象上。
.addEventListener()
对象。
< hr>
窗口
对象之前触发对象,因为它在层次结构中首先出现,但这种差异通常是无关紧要,所以你也可以选择。我发现在处理传播事件时,通常最好选择最符合您需求的事件源的最接近的对象。这将表明您可以在窗口
中选择文档
。但是,我经常移动更接近源代码,并使用 document.body
或者甚至文档中更靠近的一般父级(如果可能的话)。document.addEventListener
, but I've my own code which uses window.addEventListener
:function onBodyLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("touchmove", preventBehavior, false);
window.addEventListener('shake', shakeEventDidOccur, false);
}
document
and window
are different objects and they have some different events. Using addEventListener()
on them listens to events destined for a different object. You should use the one that actually has the event you are interested in."resize"
event on the window
object that is not on the document
object."DOMContentLoaded"
event is only on the document
object..addEventListener()
on that particular object.
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).