您的位置:首页 > Web前端 > JQuery

jQuery $.each用法

2016-03-22 00:00 447 查看
[code=plain]1.遍历数组
var arr = [ "one", "two", "three", "four"];
$.each(arr, function(index, value){
alert(this);  //this指向当前元素 //index表示Array当前下标//value表示Array当前元素
});
//上面这个each输出的结果分别为:one,two,three,four

var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]]
$.each(arr1, function(index, item_list){
alert(item_list[0]);
});
//所以上面这个each输出分别为:1   4   7

2遍历字典
var obj = { one:1, two:2, three:3, four:4};
$.each(obj, function(key, val) {
alert(obj[key]);
});
//输出结果为:1   2  3  4

3.$.each遍历json对象
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(index, obj) {
alert(obj.tagName);
});

在Chrome中,它显示在控制台下面的错误:
Uncaught TypeError: Cannot use 'in' operator to search for '156'
in [{"id":"1","tagName":"apple"}...
解决方案:JSON字符串转换为JavaScript对象。
var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}]';

$.each(JSON.parse(json), function(idx, obj) {
alert(obj.tagName);
});
//or  $.each($.parseJSON(json), function(idx, obj) {
alert(obj.tagName);
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: