Jquery模板-嵌套JSON(唯一键名)

5

请看一下这个JSON。是的,它嵌套得像地狱一样。但我需要它嵌套以保持数据层次结构。

来自firebug控制台的JSON

我的问题是键不是通用的(因为C#字典键不能相同)。它们根据数据而变化。到目前为止,我的模板看起来像这样:

<script id="customerTemplate" type="text/x-jQuery-tmpl">
        {{each $data}}
            <div class="Customer">
                <input class="CustomerId" type="hidden" value="${ $index }" />
                <div class="CustomerHeader">
                    <div class="NameAndCheckbox">
                        <input type="checkbox" checked="checked" class="CustomerCheckbox" />
                        <span class="HeadlineText">${ $index }</span>
                    </div>
                </div>
                <div class="CustomerProjectWrapper">

                    /* HOW TO ACCESS DATA WITHIN $data */
                </div>
            </div>
        {{/each}}
    </script>

如您所见,我希望访问$data中的json数据。 $data的值包含JSON,但我不知道访问该数据的语法..并且每个$data的值内部也有JSON。

我该怎么做呢?

注意:

这是我的jQuery代码:

$.template("ctmpl", $("#customerTemplate"));

$.tmpl("ctmpl", jsonobject).appendTo("#CustomerContainer");


只是提醒一下,这不是JSON,而是JavaScript对象。JSON是一种序列化格式。你可能会从服务器上接收到它作为JSON,但一旦解析它,它就只是一个对象。 - orip
好的,我之前通过Ajax调用得到了JSON(字符串)数据。这是通过以下方式完成的:var jsonobject = $.parseJSON(response);。您认为我应该使用JSON(而不是JavaScript对象)吗? - KristianB
我的问题仍然存在... 我如何遍历 $data,然后再遍历 $data$data - KristianB
1个回答

9
您可以使用类似这样的语法:{{each(index, value) array}} 来清楚地了解您正在循环遍历的索引/值。{{each}} 也可以迭代对象上的属性。

因此,如果您有以下数据:

var data = {
    testA: {
        testA1: {
            testA1A: "blahA1A",
            testA1B: "blahA1B" 
        },
        testA2: {
            testA2A: "blahA2A",
            testA2B: "blahA2B"  
        }
    },
    testB: {
        testB1: {
            testB1A: "blahB1A",
            testB1B: "blahB1B" 
        },
        testB2: {
            testB2A: "blahB2A",
            testB2B: "blahB2B" 
        },
    }
};

您可以编写如下模板:

您可以像这样编写模板:

<script id="contentTmpl" type="text/html">
    <ul>
    {{each(i, item) $data}}
        <li>${i}</li>
        <ul>
        {{each(j, subItem) item}}
            <li>${j}</li>    
            <ul>
            {{each(k, subSubItem) subItem}}
                <li>${k} = ${subSubItem}</li>
            {{/each}}
            </ul>
        {{/each}}
        </ul>
    {{/each}}
    </ul>
</script>

Sample here: http://jsfiddle.net/rniemeyer/8PLGP/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接