$.each遍历json对象
2021-07-13 23:06
标签:问题 jquery javascrip 遍历 工作 nbsp logs var code 查看一个简单的jQuery的例子来遍历一个JavaScript数组对象。 上面的代码片断工作正常,提示 “apple”, “orange” … 等,如预期一样。 下面的例子中,声明了一个JSON字符串(随附单或双引号)直接地。 在Chrome中,它显示在控制台下面的错误: 解决方案:JSON字符串转换为JavaScript对象。 $.each遍历json对象 标签:问题 jquery javascrip 遍历 工作 nbsp logs var code 原文地址:http://www.cnblogs.com/lxl57610/p/7076862.htmlvar 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);
});
问题: 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(idx, obj) {
alert(obj.tagName);
});
Uncaught TypeError: Cannot use ‘in‘ operator to search for ‘156‘
in [{"id":"1","tagName":"apple"}...
要修复它,通过标准JSON.parse()或jQuery 的 $.parseJSON 将其转换为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);
});
上一篇:jQuery 插件开发
下一篇:文案写作有哪些关键步骤?