1、第一种情况是定义一个数组,数组中有很多个对象,目标是根据用户输入的关键词,从对象中去遍历,判断是否符合匹配
var wb =[ {"bumen":"人大电话","sex":"77777777"}, {"bumen":"大人电话","sex":"88888888"}, {"bumen":"车载电话","sex":"99999999"}, ];
var newul = [];//建立一个临时数组,用于查询使用//点击搜索,则去获得输入内容,如果未空,则显示全部,如果有内容,就去遍历匹配 $('.glassbtn').on('click',function(){ var teststr = $('#teststr').val();//获得用户输入的值//先要清空数组 newul.splice(0,newul.length);if(teststr == "" || teststr == null){//清空数组 newul.splice(0,newul.length);creatpepole();//重新渲染页面
}else {
$.each(wb,function(index,obj){//console.log(obj);if(obj.bumen.indexOf(teststr)>=0){//console.log(obj);//然后填入内容newul.push(obj);}//这个下面的遍历,可以获得每个对象里的单独的文字// $.each(this,function(name,value){// if(value.indexOf(teststr)>=0){// console.log(this[4]);// newul.push(this);// }// });});console.log(newul);shaixuan();//把查询到的对象,渲染到页面上
}});
简单点的可以看这个:
- var json = [
- {"id":"1","tagName":"apple"},
- {"id":"2","tagName":"orange"},
- {"id":"3","tagName":"banana"},
- {"id":"4","tagName":"watermelon"},
- {"id":"5","tagName":"pineapple"}
- ];
- $.each(json, function(idx, obj) {
- alert(obj.tagName);
- });
2、单纯的数组的遍历
var arr = [ "one", "two", "three", "four"]; $.each(arr, function(){console.log(this);}); //上面这个each输出的结果分别为:one,two,three,four
3、数组中的数组遍历
var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]] $.each(arr1, function(i, item){ alert(item[0]); }); //其实arr1为一个二维数组,item相当于取每一个一维数组, //item[0]相对于取每一个一维数组里的第一个值 //所以上面这个each输出分别为:1 4 74、单独的循环一个对象
var obj = { one:1, two:2, three:3, four:4};$.each(obj, function (index, value) {
console.log(value);
});
//这个each就有更厉害了,能循环每一个属性 //输出结果为:1 2 3 4
5、处理一个jq对象
$('a').each(function (index, value){
console.log($(this).attr('href'));
});
6、循环网页上所有的外联属性
$('a').each(function (index, value){
var link = $(this).attr('href');
if (link.indexOf('http://') === 0) {
console.log(link);
}
});
7、循环单个的json对象
var json = [
{ 'red': '#f00' },
{ 'green': '#0f0' },
{ 'blue': '#00f' }
];
$.each(json, function () {
$.each(this, function (name, value) {
console.log(name + '=' + value);
});
});
这个例子的输出结果是 red=#f00、 green=#0f0、 blue=#00f。
8、根据标签的class属性来进行遍历
<divclass="productDescription">Red</div>
<div>Pink</div>
<divclass="productDescription">Orange</div>
<divclass="generalDescription">Teal</div>
<divclass="productDescription">Green</div>
我们使用 each() 辅助函数,取代在选择器中用 each() 方法。
$.each($('.productDescription'),function(index,value){
console.log(index + ':' + $(value).text());
});
本例中的输出结果是0:Red, 1:Orange, 2:Green。
9、最后是延迟的特效
$('#5demo').bind('click',function(e){
$('li').each(function(index){
$(this).css('background-color','orange')
.delay(index * 200)
.fadeOut(1500);
});
e.preventDefault();
});
当用户点击 ID 为 5demo 的元素时,所有的列表元素都会马上变成橙色。然后元素根据 index 值设置延迟时间 (0, 200, 400, … 毫秒) 逐个淡出。
谨记: $.each() 和 $(selector).each() 是用不同方式定义的两种不同的方法。