1)基本用法
// ARRAYS var arr = [ 'one', 'two', 'three', 'four', 'five' ]; $.each(arr, function (index, value) { console.log(value); return (value !== 'three'); }); 只输出one two
输出一个数组:
var obj = {
one: 1,
two: 2,
three: 3,
four: 4,
five: 5
};
$.each(obj, function (index, value) {
console.log(value);
});
// Outputs: 1 2 3 4 5
2) jquery中使用,比如输出所有页面中a标签的href值
$('a').each(function (index, value){ console.log($(this).attr('href')); });
3)也可以针对JSON
var json = [ { 'red': '#f00' }, { 'green': '#0f0' }, { 'blue': '#00f' } ]; $.each(json, function () { $.each(this, function (name, value) { console.log(name + '=' + value); }); });
4) 当然也可以针对.class来循环
<div class="productDescription">Red</div> <div>Pink</div> <div class="productDescription">Orange</div> <div class="generalDescription">Teal</div> <div class="productDescription">Green</div> $.each($('.productDescription'), function (index, value) { console.log(index + ':' + $(value).text()); });
其实最方便的写法
$('.productDescription').each(function () { console.log($(this).text()); });