文档选择器和窗口选择器有什么区别?
我有以下 JQuery 函数,它接受用户输入并将其显示在屏幕上。当我选择 $(document)
和 $(window)
时,该函数起作用。使用任一选择器有什么缺点?在哪里可以阅读有关这些选择器及其差异的更多信息?
先感谢您。
$(document).keypress(function(e) {
if(e.keyCode == 13) {
var id = $("input#example").val()
console.log(id);
$('#data').append(id);
}
});
I have the following JQuery function that takes user input and displays it on screen. When I select for both $(document)
and $(window)
the function works. What is the disadvantage to using either selector? Where can I read more on these selectors and their differences?
Thank you in advance.
$(document).keypress(function(e) {
if(e.keyCode == 13) {
var id = $("input#example").val()
console.log(id);
$('#data').append(id);
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
$(window)
选择器用于选择视口$(document)
选择器用于整个文档(即内的内容) code> 标记,即使它超出了视口)。
$(window)
selector is for selecting the viewport$(document)
selector is for the entire document (that is, what's inside the<html>
tag, even if it exapnds beyond the viewport).在 jQuery 中使用
window
或document
对象时dom 选择器,大多数时候你不会注意到两者之间的区别。然而,重要的是要注意它们不是同一个对象。
window
- 指视口。它用作 JavaScript 中的主要全局对象。document
-window
的直接后代;指的是 文档树的根。所有 DOM 元素都是
document
的后代,而document
是window
的直接后代。While using the
window
ordocument
object in a jQuery dom selector, most of the time you won't notice a difference between the two.However, it's important to note that they are not the same object.
window
- refers to the viewport. It's used as the main global object in JavaScript.document
- a direct descendant ofwindow
; refers to the root of the document tree.All DOM elements are a descendant of the
document
, which is a direct descendant ofwindow
.为了回答这个问题,让我从 DOM 的定义开始,即我们通常所说的“
文档
”。现在让我解释一下我发现的关于浏览上下文的内容,因为这是文档和窗口通常具有的关系 -尽管值得一提的是,
文档
可能在没有浏览上下文
的情况下存在,但您永远不应该在 jquery 中看到这种情况。用户与
文档
的主视图进行交互。视图被定义为用于向用户代理呈现文档的媒体,例如屏幕、打印、语音。主视图是默认视图,由实现Window
接口的AbstractView
对象表示。简而言之,
window
是容器,document
是内容。但我确实建议至少浏览一下相关文档,以便更好地理解。来源:
DOM、
上下文
To answer this question let me begin with the definition of the DOM, what we commonly know as "
document
".Now let me explain a little of what I found about
browsing context
s, as that is the relationship that aDocument
and aWindow
normally have—although it is important to mention that aDocument
may exist without abrowsing context
, but you should never see that with jquery.A user interacts with the main view of the
Document
. A view is defined as the media that is being used to present theDocument
to the user agent—e.g. screen, print, speech. The main view is the default view and is represented by anAbstractView
object that implements theWindow
interface.And to put it really simple,
window
is the container anddocument
is the content. But I do recommend to at least skim through the documentation of this to have a better understanding.Sources:
DOM,
contexts