如何在jQuery中将项目添加到数组中?

编程入门 行业动态 更新时间:2024-10-11 09:25:18
本文介绍了如何在jQuery中将项目添加到数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 var list = []; $.getJSON("json.js", function(data) { $.each(data, function(i, item) { console.log(item.text); list.push(item.text); }); }); console.log(list.length);

list.length始终返回0.我在firebug中浏览了JSON,它的格式正确,一切都很好.我只是似乎无法将一个项目添加到数组中,所以我缺少了什么?

list.length always returns 0. I've browsed the JSON in firebug and it's well formed and everything looks fine. I just can't seem to add an item to the array what am I missing?

推荐答案

由于$.getJSON是异步的,我认为您的console.log(list.length);代码在填充数组之前就已触发.要更正此问题,请将您的console.log语句放入回调中:

Since $.getJSON is async, I think your console.log(list.length); code is firing before your array has been populated. To correct this put your console.log statement inside your callback:

var list = new Array(); $.getJSON("json.js", function(data) { $.each(data, function(i, item) { console.log(item.text); list.push(item.text); }); console.log(list.length); });

更多推荐

如何在jQuery中将项目添加到数组中?

本文发布于:2023-11-12 11:19:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581351.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   组中   项目   如何在   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!