简体   繁体   English

jQuery“包装器”对象的澄清

[英]Clarification of jQuery "wrapper" object

I have a doubt about the jQuery core.我对 jQuery 核心有疑问。 From the docs and a couple of books I get:从文档和几本书我得到:

var obj = $("div");

Which returns a wrapper object AKA a collection of selected DOM elements with additional methods (correct me if I'm wrong).它返回一个包装器对象 AKA 一个选定 DOM 元素的集合,带有附加方法(如果我错了,请纠正我)。 I've read the jQuery function $() returns a wrapper object, or does it really return a copy of jQuery plus a collection of wrapped elements?我读过 jQuery 函数$()返回一个包装对象,还是它真的返回 jQuery 的副本加上包装元素的集合?

It returns an instance of a jQuery object, wrapping the elements you selected with your CSS selector (in this case, a jQuery object wrapping all the divs in the document).它返回一个 jQuery 对象的实例,用 CSS 选择器包装您选择的元素(在本例中,一个 jQuery 对象包装文档中的所有 div)。

jQuery isn't something that is "copied" - it is behavior that is wrapped around elements in the DOM. jQuery 不是“复制”的东西——它是围绕 DOM 元素的行为。

var jqDivs = $("div");
var jqButtons = $("button");
var jqSubmitButton = $("button#submit");

Those 3 vars reference 3 different objects.这 3 个变量引用了 3 个不同的对象。 All of them implement the same jQuery behaviors, but they do it upon different elements.它们都实现了相同的 jQuery 行为,但它们是在不同的元素上实现的。 jqDivs.hide() would hide the divs - jqButtons.hide() would hide the buttons, and jqSubmitButton.hide() would hide only the button with id=submit. jqDivs.hide() 将隐藏 div - jqButtons.hide() 将隐藏按钮,而 jqSubmitButton.hide() 将仅隐藏 id=submit 的按钮。

The term "wrap" is a bit misleading to me. “包装”这个词对我来说有点误导。 jQuery keeps references to elements matched by the supplied selector as numeric properties of the jQuery instance returned by the call, so: jQuery 保留对由提供的选择器匹配的元素的引用作为调用返回的 jQuery 实例的数字属性,因此:

var allTheDivs = $('div');

returns a jQuery object with references to all the divs in the document, and:返回一个引用文档中所有 div 的 jQuery 对象,并且:

allTheDivs[0];  // or allTheDivs['0'];

is a reference to the first one.是对第一个的引用。 So if you then do:所以如果你这样做:

allTheDivs.hide();

it calls the hide method of the jQuery instance allTheDivs which cycles over all the referenced elements and hides them.它调用 jQuery 实例allTheDivshide方法,该方法循环遍历所有引用的元素并隐藏它们。 But don't try:但不要尝试:

allTheDivs['0'].hide()

as that will try to call hide on a DOM element, which probably won't exist so will restult in an error.因为这将尝试在可能不存在的 DOM 元素上调用hide ,因此会导致错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM