knockout.js - 前置于那些生成的

时间:2014-11-02 22:39:43

标签: javascript knockout.js

虽然我的viewmodel看起来像这样:

    "rows" : [
        {   "name": "row_1",
            "columns": [
                { "name" : "column_1", "value" : "value_1_1"},
                { "name" : "column_2", "value" : "value_1_2"},
                { "name" : "column_3", "value" : "value_1_3"},
                { "name" : "column_4", "value" : "value_1_4"},
                { "name" : "column_5", "value" : "value_1_5"}
            ]
        },
        {   "name": "row_2",
            "columns": [
                { "name" : "column_1", "value" : "value_2_1"},
                { "name" : "column_2", "value" : "value_2_2"},
                { "name" : "column_3", "value" : "value_2_3"},
                { "name" : "column_4", "value" : "value_2_4"},
                { "name" : "column_5", "value" : "value_2_5"}
            ]
        },
        ...
     ]

我用以下内容构建了一个表:

<tbody data-bind="foreach: rows">
  <tr data-bind="foreach: columns">
     <td><span data-bind="text: value"></span></td>
  </tr>
</tbody>

这一切都很好,但我希望每一行都有一个<td>(row_name)</td>前缀。

是否有一种直接的方式来预先添加“标签”<td>

1 个答案:

答案 0 :(得分:5)

这应该这样做:

<tbody data-bind="foreach: rows">
    <tr>
        <td data-bind="text: name"></td>
        <!-- ko foreach: columns -->
            <td><span data-bind="text: value"></span></td>
        <!-- /ko -->
    </tr>
</tbody>

这种方法被称为“无容器控制流语法”,非常适合这种情况; KO文档给出了这个例子:

<ul>
    <li class="header">Header item</li>
    <!-- ko foreach: myItems -->
        <li>Item <span data-bind="text: $data"></span></li>
    <!-- /ko -->
</ul>

参考:http://knockoutjs.com/documentation/foreach-binding.html