jQuery 对象和 DOM 元素 [英] jQuery object and DOM element
问题描述
我想了解 jQuery 对象和 DOM 元素之间的关系..
当 jQuery 返回一个元素时,它在警报中显示为 [object Object]
.当 getElementByID
返回一个元素时,它显示为 [object HTMLDivElement]
.这究竟是什么意思?我的意思是他们两个对象都有区别吗?
还有哪些方法可以对 jQuery 对象和 DOM 元素进行操作?一个 jQuery 对象可以代表多个 DOM 元素吗?
我想了解 jQuery 对象和 DOM 元素之间的关系
jQuery 对象是一个类似数组的对象,它包含 DOM 元素.一个 jQuery 对象可以包含多个 DOM 元素,具体取决于您使用的选择器.
<块引用>还有哪些方法可以对 jQuery 对象和 DOM 元素进行操作?一个 jQuery 对象可以代表多个 DOM 元素吗?
jQuery 函数(完整列表在网站上)作用于 jQuery 对象而不是 DOM 元素.您可以使用 .get()
或直接访问所需索引处的元素来访问 jQuery 函数内的 DOM 元素:
$("selector")[0]//访问这个 jQuery 对象中的第一个 DOM 元素$("selector").get(0)//相当于上面的代码$("selector").get()//检索与此选择器匹配的 DOM 元素的真实数组
换句话说,以下应该得到相同的结果:
警报($(#foo")[0]);警报($("#foo").get(0));警报(document.getElementById(foo"));
有关 jQuery 对象的更多信息,请查看文档.另请查看 .get()
I would like to understand relationship between jQuery object and DOM element..
When jQuery returns an element it shows up as [object Object]
in an alert.
When getElementByID
returns an element it shows up as [object HTMLDivElement]
. What does that mean exactly? I mean are both of them objects with a difference ?
Also what methods can operate on jQuery object vs DOM element? Can a single jQuery object represent multiple DOM elements ?
I would like to understand relationship between jQuery object and DOM element
A jQuery object is an array-like object that contains DOM element(s). A jQuery object can contain multiple DOM elements depending on the selector you use.
Also what methods can operate on jQuery object vs DOM element? Can a single jQuery object represent multiple DOM elements ?
jQuery functions (a full list is on the website) operate on jQuery objects and not on DOM elements. You can access the DOM elements inside a jQuery function using .get()
or accessing the element at the desired index directly:
$("selector")[0] // Accesses the first DOM element in this jQuery object
$("selector").get(0) // Equivalent to the code above
$("selector").get() // Retrieve a true array of DOM elements matched by this selector
In other words, the following should get you the same result:
<div id="foo"></div>
alert($("#foo")[0]);
alert($("#foo").get(0));
alert(document.getElementById("foo"));
For more information on the jQuery object, see the documentation. Also check out the documentation for .get()
这篇关于jQuery 对象和 DOM 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!