Difference between document.addEventListener and window.addEventListener?

后端 未结 3 889
遇见更好的自我
遇见更好的自我 2020-12-02 04:24

While using PhoneGap, it has some default JavaScript code that uses document.addEventListener, but I have my own code which uses window.addEventListener

3条回答
  •  没有蜡笔的小新
    2020-12-02 05:27

    You'll find that in javascript, there are usually many different ways to do the same thing or find the same information. In your example, you are looking for some element that is guaranteed to always exist. window and document both fit the bill (with just a few differences).

    From mozilla dev network:

    addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, the document itself, a window, or an XMLHttpRequest.

    So as long as you can count on your "target" always being there, the only difference is what events you're listening for, so just use your favorite.

提交回复
热议问题