【问题标题】:Creating a multicolum HTML table with jQuery templates and knockoutjs使用 jQuery 模板和 knockoutjs 创建多列 HTML 表
【发布时间】:2011-09-14 18:37:16
【问题描述】:

我有以下代码(也在jsfiddle 中):

<table>
    <thead><tr><th>Equation</th><th>Equation</th></tr></thead>
<tbody data-bind="template: {name: 'equationTemplate', foreach: equations}"></tbody>
</table>

<script language="javascript" type="text/javascript">

</script>

<script type="text/x-jquery-tmpl" id='equationTemplate'>
    <!-- In here I want to be able to break it up into two 
    columns of two rather than one column of four-->
    <tr>
        <td>${first}+${second}=<input data-bind="value: answer"/></td>
    </tr>
</script>

有了这个 JS:

$(document).ready(function () {

    var viewModel = {
        equations: ko.observableArray([
            { first: 1, second: 2, answer: 3 },
            { first: 4, second: 4, answer: 8 },
            { first: 10, second: 10, answer: 20 }, 
            { first: 5, second: 5, answer: 10}])
    };

    ko.applyBindings(viewModel);
});

如何修改模板以将其输出到两行两列的表格中?方程 10+10=20 和 5+5=10 应出现在第二列中。

非常感谢任何帮助。

【问题讨论】:

    标签: knockout.js jquery-templates


    【解决方案1】:

    一个选项是切换到{{each}}而不是模板绑定的foreach选项,这样你就可以访问索引了。使用 {{each}} 的缺点是,如果动态添加/删除任何方程,您的模板将被完全重新渲染。

    看起来像:

    <table>
        <thead><tr><th>Equation</th><th>Equation</th></tr></thead>
    <tbody data-bind="template: { name: 'equationTemplate', foreach"></tbody>
    </table>
    
    <script type="text/x-jquery-tmpl" id='equationTemplate'>
        {{each equations}}
            {{if $index % 2 == 0}}<tr>{{/if}}
                <td>${first}+${second}=<input data-bind="value: answer"/></td>
            {{if $index % 2 == 1}}</tr>{{/if}}   
        {{/each}}
    </script>
    

    示例:http://jsfiddle.net/rniemeyer/QESBn/1/

    另一种选择是构建一个dependentObservable,它在映射到行/列的结构中表示您的数据。

    这是一个示例:http://jsfiddle.net/rniemeyer/QESBn/2/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      • 1970-01-01
      • 2018-09-21
      • 2015-11-10
      相关资源
      最近更新 更多