jQuery 的 .each()
方法是用于遍历 jQuery 对象或数组/类数组对象的常用方法。在遍历过程中,它会为每个元素提供一个索引值。
// 遍历 jQuery 对象
$(selector).each(function(index, element) {
// 处理代码
});
// 遍历数组或类数组对象
$.each(arrayOrObject, function(index, value) {
// 处理代码
});
$('li').each(function(index, element) {
console.log('索引:', index, '文本内容:', $(element).text());
});
var colors = ['red', 'green', 'blue'];
$.each(colors, function(index, value) {
console.log('索引:', index, '颜色:', value);
});
var person = {name: 'John', age: 30, city: 'New York'};
$.each(person, function(key, value) {
console.log('属性:', key, '值:', value);
});
解决方案:在回调函数中返回false
可以终止循环
$('li').each(function(index) {
if (index === 2) return false; // 终止循环
console.log(index);
});
解决方案:返回true
(或任何非false值)相当于continue
$('li').each(function(index) {
if (index === 1) return true; // 跳过索引1
console.log(index);
});
原因:这通常发生在遍历对象而非数组时,jQuery会按照对象属性的枚举顺序提供索引
解决方案:如果需要固定顺序,可以先转换为数组再遍历
var obj = {b: 2, a: 1};
var arr = Object.keys(obj).sort().map(function(key) {
return {key: key, value: obj[key]};
});
$.each(arr, function(index, item) {
console.log(index, item.key, item.value);
});
Array.prototype.forEach()