jQuery $.each() multidimensional JSON array
What did I manage do do wrong here? I can't see it, through the first $.each it works, get to the second it stops..
var testJSON = {"cluster":[{"node":[{"name":"one", "number":'100', "error":"none"},{"name":"two", "number":'200', "error":"none"},{"name":"three", "number":'300', "error":"found"},{"name":"four", "number":'400', "error":"none"}]}]}
if (testJSON.cluster.length != 0)
{
$.each(testJSON.cluster, function(i, clstr)
{
开发者_StackOverflow中文版 $('.clusters').append('<ul class="nodes">');
$.each(clstr.node, function(i, ndes)
{
$.find('ul').append('<li>'+ndes.name+'</li>');
});
$('.clusters').append('</ul>');
});
}
Change your code to the following:
if (testJSON.cluster.length != 0) {
$.each(testJSON.cluster, function(i, clstr) {
$('.clusters').append('<ul class="nodes"></ul>');
$.each(clstr.node, function(i, ndes) {
$('.clusters ul.nodes').append('<li>' + ndes.name + '</li>');
});;
});
}
When you append an element, you don't have to later append the closing tag. Also, find
cannot be called directly from the jQuery object. You need a selector.
What is $.find
, you are getting an exception in the inner loop and then it stops.
$.find('ul').append('<li>'+ndes.name+'</li>');
Are you looking for the ul
which you added in the outer loop? If yes, then use
$('.clusters ul').append('<li>'+ndes.name+'</li>')
精彩评论