返回目录
已经写了很多knockoutjs的文章了,今天在review代码时,忽然看到一个问题,在knockout环境下,如何遍历一个简单的数组?对于遍历对象组件的数组来说,很容易,直接foreach:对象名,然后进行属性的绑定即可,而如下数据[10,20,30]这种简单的数组,如何去遍历呢?在阅读knockout官网后,找到了答案,如下实例:
<label>博主</label> <div data-bind="text:User.title"></div> <label>地域</label><div data-bind="text:User.address"></div> <label>所经历的等级 </label> <ul data-bind="foreach:Level"> <li>索引:<span data-bind="text: $index"></span>,数值:<span data-bind="text: $data"></span></li> </ul> <label>所购买的 </label> <div data-bind="foreach:SaleDetail"> [<span data-bind="text:id"></span>] <span data-bind="text:memo"></span> [<a href="javascript:;" data-bind="click:$parent.remove">移除</a>]<hr /> </div> <script type="text/Javascript"> var Demo = function () { var self = this; self.User = { title: "test knockout js", address: "beijing" }; self.Level = [10, 20, 30, 40, 50]; self.SaleDetail = ko.observableArray([ { id: 1, memo: '2005-01,消费购买了水壶' }, { id: 2, memo: '2006-03,消费购买了手机' }, { id: 3, memo: '2006-10,消费购买了手机' } ]); for (var i = 0; i < 5; i++) { self.SaleDetail.push({ id: i + 4, memo: '2005-01,消费购买了水壶' }) } self.remove = function () { self.SaleDetail.remove(this); } } ko.applyBindings(new Demo()); </script>
重要看一下HTML部分
QQcNISDTOQVcBZRCCIAgy+sktg+IsluUig4reFDdBVcHk3NA8C/8IKYycjFIZJBultIYIQZAqBK5c4Z9/zgcH+blz8P77cOIEHD0Kb7wBBw/C/v2su5tt385eeol2dbGXxmlbt7Pubti/Hw4ehDfegKNH4cQJeP99fu4cHxzkn38OV66kfUJI0cghgwwt69Xg3NipqH2m/99WbBkEumplAkWKKy9AU7KFqg6ciyXRNaW9ZLSL6h6u2TXdw1115a/ptCm1MxHBNT4bI1Msd0gNDVQ1W25LBFOX1wwW2lPRyZ4Wt2VQsKaVcclYojNGKkSCvTu+HPv/e9ajI7XTksmgMMSra5QDV6/yoSH+ySf83Dk4dQqOHYO+PujthT172PbtrLOTdXay7dthzx7o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