0

我想在一个 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()) 有什么区别?为什么我不能在我的代码中使用第一个?

4

1 回答 1

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
于 2012-08-09T19:37:08.243 回答