JQuery $.each遍历JavaScript数组对象实例_jquery_脚本之家

2019-12-02 23:34栏目:竞技宝竞猜
TAG:

查看一个简单的jQuery的例子来遍历一个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, function {alert;

上面的代码片断工作正常,提示 “apple”, “orange” … 等,如预期一样。问题: JSON 字符串

下面的例子中,声明了一个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 {alert;

在Chrome中,它显示在控制台下面的错误:

Uncaught TypeError: Cannot use 'in' operator to search for '156' in [{"id":"1","tagName":"apple"}...

解决方案:JSON字符串转换为JavaScript对象。要修复它,通过标准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, function {alert;//or $.each, function {alert;

版权声明:本文由龙竞技官网发布于竞技宝竞猜,转载请注明出处:JQuery $.each遍历JavaScript数组对象实例_jquery_脚本之家