如何通过剔除ViewModel集合进行迭代 [英] how to iterate through knockout viewmodel collection
本文介绍了如何通过剔除ViewModel集合进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法使用Knockout.js库显示产品项目.
Iam not able to display product items with Knockout.js library.
HTML
<p>First product: <strong data-bind="text: products[0].description"></strong></p>
<tbody data-bind="foreach: products">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: description"></td>
</tr>
</tbody>
JavaScript
<script type='text/javascript'>
$(function () {
var json = {
"products": [
{ "id": 1, "description": "product A" },
{ "id": 2, "description": "product B" },
{ "id": 3, "description": "product C" }
]
}
function viewModel() {
this.products = json.products;
}
ko.applyBindings(new viewModel());
});
</script>
我没有收到任何错误消息,但只看到第一产品:"文本.我想念什么?
I do not get any error message, but i see only "First product:" text. What am I missing ?
推荐答案
我在下面的jsfiddle中运行它: https://jsfiddle.net/3np0hqp7/2/
I got it working in the follwing jsfiddle: https://jsfiddle.net/3np0hqp7/2/
HTML:
<p>First product: <strong data-bind="text: products[0].description"></strong></p>
<table>
<tbody data-bind="foreach: products">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: description"></td>
</tr>
</tbody>
</table>
JS:
(function() {
var viewModel = {
products: [
{ id: 1, description: "product A" },
{ id: 2, description: "product B" },
{ id: 3, description: "product C" }
]
}
ko.applyBindings(viewModel);
}());
您在主函数末尾缺少括号()
,表示该函数应立即执行.
此外,您可以为双向绑定创建可观察对象.
You were missing the parenthesis ()
at the end of the main function, to denote that the function should be executed right away.
Furthermore, you can create observables for two-way binding.
这篇关于如何通过剔除ViewModel集合进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文