从 jQuery 对象获取基本元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the base element from a jQuery object
提问by dansays
I'm struggling to find the right terminology here, but if you have jQuery object...
我正在努力在这里找到正确的术语,但是如果您有 jQuery 对象...
$('#MyObject')
...is it possible to extract the base element? Meaning, the equivalent of this:
...是否可以提取基本元素?意思是,相当于:
document.getElementById('MyObject')
采纳答案by VolkerK
Yes, use .get(index)
. According to the documentation:
是的,使用.get(index)
. 根据文档:
The
.get()
method grants access to the DOM nodes underlying each jQuery object.
该
.get()
方法授予对每个 jQuery 对象底层 DOM 节点的访问权限。
回答by Aaron Wagner
$('#MyObject').get(0);
I think that's what you want. I think you can also reference it like a regular array with:
我想这就是你想要的。我认为您也可以像使用常规数组一样引用它:
$('#MyObject')[0];
But I'm not sure if that will always work. Stick with the first syntax.
但我不确定这是否总是有效。坚持第一种语法。
回答by Shog9
A jQuery object is a set of elements. In your case, a set of one element. This differs from certain other libraries, which wrap single elements and provide alternate syntax for selectors that return multiple matches.
jQuery 对象是一组元素。在您的情况下,一组一个元素。这与某些其他库不同,后者包装单个元素并为返回多个匹配项的选择器提供替代语法。
Aaron Wand VolkerKalready explained how to access the first (index 0) element in the set.
回答by VeeTheSecond
I tested Aaron's statements on all the browsers I have available on my box:
我在我的盒子上可用的所有浏览器上测试了 Aaron 的语句:
$('#MyObject').get(0);
vs
对比
$('#MyObject')[0];
As far as I can tell, it is only a matter of personal preference.
据我所知,这只是个人喜好问题。
Functionally, both these statements are equivalent for both existing and non-existing elements. I tested the following browsers: Chrome 27.0, FF 21.0, IE10, IE9, IE8, IE7, IE6.
在功能上,这两个语句对于现有和不存在的元素都是等效的。我测试了以下浏览器:Chrome 27.0、FF 21.0、IE10、IE9、IE8、IE7、IE6。
In the speed tests that I ran, it was not always possible to tell which variation was faster; the outcome was not always consistent, even on the same browser. For the speed tests, I only tested existing elements. My test results are here.
在我运行的速度测试中,并不总是可以判断哪个变体更快;结果并不总是一致的,即使在同一个浏览器上也是如此。对于速度测试,我只测试了现有元素。我的测试结果在这里。