简体   繁体   English

对象# <HTMLDivElement> 作为jQuery对象

[英]Object #<HTMLDivElement> as jQuery object

How can I get a #<HTMLDivElement> as a jQuery object? 如何获得#<HTMLDivElement>作为jQuery对象?

I need to do the following: I have a list of div's with the class contents. 我需要执行以下操作:我有一个包含类内容的div列表。 So I iterate over it until I find the one with the additional class: "test" 所以我遍历它,直到找到具有其他类的“测试”

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'

The each() function gives you DOM object and you have to convert it to jQuery object. each()函数为您提供DOM对象,您必须将其转换为jQuery对象。 You can pass value to $ jQuery function to convert it to jQuery object. 您可以将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")

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"类的元素。

DEMO: http://jsfiddle.net/xfErG/ 演示: http : //jsfiddle.net/xfErG/

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'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM