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