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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:18:52  来源:igfitidea点击:

How do I access the original element from the jQuery wrapper

javascriptjquerywrapper

提问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 wrapto 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 getto 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

You can use get()to retrieve the HTML element.

您可以使用get()来检索 HTML 元素。

var orig = wrap.get(0);

However, if wrapconsists of multiple elements, you will need to know the correct index which to use when you use the get()function.

但是,如果wrap由多个元素组成,您将需要知道在使用该get()函数时要使用的正确索引。

回答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 wrapwithout $()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;