jQuery $.each()多维JSON数组

jQuery $.each() multidimensional JSON array

本文关键字:多维 JSON 数组 each jQuery      更新时间:2023-09-26

我在这里做错了什么?透过第一层,我看不见它。每次都有效,直到第二次停止。

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)
    {
        $('.clusters').append('<ul class="nodes">');
        $.each(clstr.node, function(i, ndes)
        {
            $.find('ul').append('<li>'+ndes.name+'</li>');
        });
        $('.clusters').append('</ul>');
    });
}

将代码修改为:

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>');
        });;
    });
}

当你添加一个元素时,你不需要再添加结束标记。而且,不能直接从jQuery对象调用find。你需要一个选择器

什么是$.find,你在内部循环中得到一个异常,然后它停止。

$.find('ul').append('<li>'+ndes.name+'</li>');

你是在寻找你在外环中添加的ul吗?如果是,则使用

$('.clusters ul').append('<li>'+ndes.name+'</li>')