jQuery loop through json?

回眸只為那壹抹淺笑 提交于 2019-12-08 19:13:44

问题


I have some json (var data)that looks like this:

{"success":"true","keywords":["firstkeyword","secondkeyword"]}

And im trying to loop through the keywords using this code:

            data.keywords.each(function(e){
                $('#campaign_keywords').append("<p>"+e+"</p>");
            });

But i get the error

Uncaught TypeError: Object firstkeyword,secondkeyword has no method 'each' 

回答1:


You need to loop through it like this:

$.each(data.keywords, function (i, v) {
    $('#campaign_keywords').append("<p>"+data.keywords[i]+"</p>");
});

jQuery.each()




回答2:


That's because it's an array and it needs to be a jquery wrapped object in order to use jquery functions. Try:

$.each(data.keywords, function(index, value){...});



回答3:


Its a javascript array, not jQuery object. just apply $ over it to make it jquery object like

    $(data.keywords).each(function(e){
        $('#campaign_keywords').append("<p>"+e+"</p>");
    });


来源:https://stackoverflow.com/questions/13980113/jquery-loop-through-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!