在jQuery中,.each()
是一个常用的迭代方法,用于遍历jQuery对象集合中的每个元素。当需要处理一组输入元素并获取它们的类时,.each()
方法非常有用。
$('input').each(function(index, element) {
// 在这里处理每个input元素
var classes = $(element).attr('class');
console.log(classes);
});
假设有以下HTML结构:
<input type="text" class="form-control input-lg" id="name">
<input type="email" class="form-control input-sm" id="email">
<input type="password" class="form-control" id="password">
$('input').each(function() {
var classes = $(this).attr('class');
console.log(classes);
// 输出:
// "form-control input-lg"
// "form-control input-sm"
// "form-control"
});
$('input').each(function() {
var className = $(this).prop('className');
console.log(className);
});
$('input').each(function(index, element) {
var className = element.className;
console.log(className);
});
$('input').each(function() {
var classList = $(this).attr('class').split(' ');
console.log(classList);
// 输出:
// ["form-control", "input-lg"]
// ["form-control", "input-sm"]
// ["form-control"]
});
attr('class')
会返回undefined
,所以在使用前应该检查:attr('class')
会返回undefined
,所以在使用前应该检查:.split(' ')
将类字符串转换为数组时,如果元素没有类,会抛出错误,应该先检查:.split(' ')
将类字符串转换为数组时,如果元素没有类,会抛出错误,应该先检查:.hasClass()
方法:.hasClass()
方法:问题:获取的类名是undefined
问题:类名字符串分割后有空字符串
问题:动态添加的元素无法获取类