javascript 如何从 jQuery 包装器访问原始元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6623258/
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
How do I access the original element from the jQuery wrapper
提问by brb
Assuming I have this:
假设我有这个:
var wrap = $("#someId");
I need to access the original object that I would get by
我需要访问我将得到的原始对象
var orig = document.getElementById("someId");
But I don't want to do a document.getElementById
.
但我不想做一个document.getElementById
.
Is there something I can use on wrap
to get it? something like:
有什么我可以wrap
用来得到它的东西吗?就像是:
var orig = wrap.original();
I searched high and low but I didn't find anything; or maybe I'm not looking for the right thing.
我四处寻找,但没有找到任何东西;或者也许我不是在寻找正确的东西。
回答by lonesomeday
The function for this is get
. You can pass an index to get
to access the element at that index, so wrap.get(0)
gets the first element (note that the index is 0-based, like an array). You can also use a negative index, so wrap.get(-2)
gets the last-but-one element in the selection.
这个函数是get
。您可以传递索引以get
访问该索引处的元素,因此wrap.get(0)
获取第一个元素(请注意,索引是从 0 开始的,就像数组一样)。您还可以使用负索引,以便wrap.get(-2)
获取选择中的最后一个元素。
wrap.get(0); // get the first element
wrap.get(1); // get the second element
wrap.get(6); // get the seventh element
wrap.get(-1); // get the last element
wrap.get(-4); // get the element four from the end
You can also use array-like syntax to access elements, e.g. wrap[0]
. However, you can only use positive indexes for this.
您还可以使用类似数组的语法来访问元素,例如wrap[0]
. 但是,您只能为此使用正索引。
wrap[0]; // get the first element
wrap[1]; // get the second element
wrap[6]; // get the seventh element
回答by Hyman Franklin
$("#someId")
will return a jQuery object, so to get at the actual HTML element you can do:
$("#someId")
将返回一个 jQuery 对象,因此要获取实际的 HTML 元素,您可以执行以下操作:
wrap[0]
or wrap.get(0)
.
wrap[0]
或wrap.get(0)
。
回答by Niklas
回答by Hyman Murdoch
You can just use var orig = wrap[0];
as far as I know, if there's more than one element. If there's just the one, you can just use wrap
without $()
around it.
var orig = wrap[0];
据我所知,如果有多个元素,您可以使用。如果只有一个,你可以wrap
不用$()
在它周围使用。
回答by Michael Wright
You can use wrap still.. Wrap is the same as 'orig' would be in the above! :)
您仍然可以使用 wrap .. Wrap 与上面的 'orig' 相同!:)
If you really want:
如果你真的想要:
var orig = wrap;