使用 jQuery 模板和 knockoutjs 创建多列 HTML 表格
我有以下代码(也在 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 应出现在第二列中。
非常感谢任何帮助。
I have the following code (also in a 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>
With this 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);
});
How would I modify the template to output this in a table of two rows and two columns? Equations 10+10=20 and 5+5=10 should appear in the second column.
Any help greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种选择是切换到
{{each}}
而不是模板绑定的foreach
选项,以便您可以访问索引。使用 {{each}} 的缺点是,如果动态添加/删除任何方程,您的模板将完全重新渲染。它看起来像:
示例如下: http://jsfiddle.net/rniemeyer/QESBn/1/
另一种选择是构建一个 dependentObservable,它以映射到行/列的结构表示您的数据。
这是一个示例: http://jsfiddle.net/rniemeyer/QESBn/2/
One option is to switch to
{{each}}
instead of theforeach
option of the template binding, so that you have access to the index. The disadvantage to using {{each}} is that your template will be re-rendered completely if any equations are added/removed dynamically.It would look like:
Sample here: http://jsfiddle.net/rniemeyer/QESBn/1/
Another alternative would be to build a dependentObservable that represents your data in a structure that maps to rows/columns.
Here is a sample: http://jsfiddle.net/rniemeyer/QESBn/2/