javascript 对象 #<HTMLDivElement> 作为 jQuery 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16396074/
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
Object #<HTMLDivElement> as jQuery object
提问by gurehbgui
How can I get a #<HTMLDivElement>
as a jQuery object?
如何将 a#<HTMLDivElement>
作为 jQuery 对象?
I need to do the following: I have a list of div's with the class contents. So I iterate over it until I find the one with the additional class: "test"
我需要执行以下操作: 我有一个包含类内容的 div 列表。所以我迭代它,直到找到带有附加类的那个:“测试”
here is my code:
这是我的代码:
$.each( $(".contents"), function( key, value ) {
if (value.hasClass("test"))
{
alert("got it");
}
});
I'm getting the exception: Uncaught TypeError: Object #<HTMLDivElement> has no method 'hasClass'
我收到异常: Uncaught TypeError: Object #<HTMLDivElement> has no method 'hasClass'
回答by Adil
The each()
function gives you DOM
object and you have to convert it to jQuery
object. You can pass value
to $
jQuery function to convert it to jQuery object.
该each()
函数为您提供DOM
对象,您必须将其转换为jQuery
对象。您可以传递value
给$
jQuery 函数以将其转换为 jQuery 对象。
$.each( $(".contents"), function( key, value ) {
if ($(value).hasClass("test"))
{
alert("got it");
}
});
You do not need to iterate through each and simplify it like
您不需要遍历每个并简化它
elements = $(".contents.text")
回答by VisioN
Why not to do it simpler with:
为什么不这样做更简单:
$(".contents.test"). ...
Here jQuery will select element that has both "contents"
and "test"
classes set.
这里 jQuery 将选择同时设置"contents"
和"test"
类的元素。
回答by Quentin
The main jQuery function can accept a DOM Element as its argument.
主要的 jQuery 函数可以接受一个 DOM 元素作为它的参数。
var foo = jQuery(HTMLElementNode);
The following two lines of code have the same end result:
以下两行代码具有相同的最终结果:
var foo = jQuery('#foo');
var foo = jQuery(document.getElementById('foo'));