使用Knockout JS和Jquery模板进行递归tr [英] Recursive tr with Knockout JS and Jquery Template

查看:116
本文介绍了使用Knockout JS和Jquery模板进行递归tr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图为我的问题找到解决方案,我发疯了.我有一个JS对象,它具有层次结构,层次结构级别未知.利用JQuery模板和Knockout JS,我可以使用<ul>& <li>,但我的要求是,对于每个孩子,我都需要在Table中渲染一个新的Row.因此,可以说我的结构是:

I am going crazy trying to find a solution for my problem. I have a JS object which has a hierarchical structure and the level of hierarchy is unknown. Making use of JQuery template and Knockout JS i can get the tree structure with <ul> & <li> but my requirement is, for each child, I need to render a new Row in a Table So lets say my structure is:

{
    Name: 'First', 
    Total: 100,
    Set: [
        { 
            Name: 'First_1', Total: 30,
            Set: [{Name: 'First_1_1', Total: 10}, {Name: 'First_1_2', Total: 20}]  
        },
        { Name: 'First_2', Total: 0 }
    ]
}

该表应如下所示:

<table width="100%">
    <tbody>
    <tr><th>Name</th><th>Total</th></tr>
    <tr><td>First</td><td>100</td></tr>
    <tr><td>First_1</td><td>30</td></tr>
    <tr><td>First_1_1</td><td>10</td></tr>
    <tr><td>First_1_2</td><td>20</td></tr>
    <tr><td>First_2</td><td>0</td></tr>
    </tbody>
</table>

以下是我想出的小提琴: http://jsfiddle.net/paragnair/xpsa4/

Following is the fiddle I have come up with: http://jsfiddle.net/paragnair/xpsa4/

如果我使用的是ul li,则可以使用来递归地调用模板

If I was using ul li, i could call the template recursively by using

<ul data-bind="template: {name: 'tree1', foreach: Set}"></ul>

但是由于模板本身以<tr>开头,所以我不确定如何在不使用data-bind="template:{...}部分编写节点的情况下调用模板?初始调用将起作用,因为它在<tbody>上,但是我不能在tbody中包含tbody来递归调用模板以呈现其他tr.

but since my template itself starts with a <tr> I am not sure how do i call the template without writing a node with the data-bind="template:{...} part? The initial call will work because its on the <tbody> but I cannot have a tbody within a tbody to recursively call the template to render other tr.

我希望这种解释是足够的.让我知道您是否需要更多详细信息.感谢您的帮助.

I hope this explanation was sufficient. Let me know if you need more details. Any help is appreciated.

推荐答案

您可以从该模板内部递归调用模板,该模板与foreach的$ data上下文属性结合使用,可以完成您正在寻找的工作...我在解释问题时很糟糕,所以我更新了您的jsfiddle以执行您想要的操作, http://jsfiddle .net/xpsa4/5/

You can recursively call a template from inside that template, that combined with the foreach's $data context property allows you do do what you're looking for... I'm terrible at explaining things so I updated your jsfiddle to do what you're looking for, http://jsfiddle.net/xpsa4/5/

这篇关于使用Knockout JS和Jquery模板进行递归tr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆