jquery .each(函数(索引,元素))不工作?

时间:2012-08-09 19:33:54

标签: jquery html css

我想在div中获取所有子标签:

<div class="form input">
            <label class="formLabel cFont cColor cMore" id="text" for="textInput">please input something</label>
            <input class="formInput" type="text" id="textInput">
            <label class="formLabel" id="check" for="checkboxInput">check here to toggle disable</label>
            <input class="formInput" type="checkbox" id="checkboxInput">
        </div>
        <button type="button" onclick="showClasses()">show classes</button>

我做了以下事情:

function showClasses(){
        var children = $('.form').children();
        children.each(function(index, v){
            var classes = v.attr('class');
            console.log(classes);
        }); // end each
    } // end showClasses

并且控制台给了我一个错误:

Uncaught TypeError: Object #<HTMLLabelElement> has no method 'attr'

然后,我将代码更改为:

function showClasses(){
        var children = $('.form').children();
        children.each(function(){
            var classes = $(this).attr('class');
            console.log(classes);
        }); // end each
    } // end showClasses

然后它有效。

那么.each(function(index,element))和.each(function())之间的区别是什么?为什么我不能在我的代码中使用第一个?

1 个答案:

答案 0 :(得分:1)

children.each(function(index, v){ - v中是domElement。尝试使用下面的.attr

var classes = $(v).attr('class');

完整代码:

function showClasses(){
    var children = $('.form').children();
    children.each(function(index, v){
        var classes = $(v).attr('class');
        console.log(classes);
    }); // end each
} // end showClasses