[英]looping through Javascript array and displaying HTML (knockout)
I want to display JSON data which is my model. 我想显示我的模型的JSON数据。 This is an example of what could be in it:
这是其中可能存在的示例:
{"id":"1","name":"1","category":"A" },
{"id":"2","name":"2","category":"B" },
{"id":"3","name":"3","category":"A" },
{"id":"4","name":"4","category":"B" }
What I want is distinct al categories with javascript into an array i guess: A B. 我想要的是将不同的al类别与javascript组合成一个数组,我想:
And then foreach element in array matching cat A print it like so with knockout: 然后在匹配cat A的数组中的foreach元素像这样用剔除进行打印:
<div data-bind="template: { name: template, foreach: LISTOFITEMS }"></div>
<script id="template">
<h1 data-bind="text: Category></h1>
<div data-bind=" foreach: LISTOFITEMSmatchingcategory ">
<li data-bind="text: name"></li>
</div>
</script>
Is this the way to go? 这是要走的路吗? I want to make stuff easily sortable (the array is an observable array)
我想使东西易于排序(该数组是一个可观察的数组)
Try the following way: - 请尝试以下方式:-
var self = this; self.listArr = ko.observableArray([ {"id":"1","name":"1","category":"A" }, {"id":"2","name":"2","category":"B" }, {"id":"3","name":"3","category":"A" }, {"id":"4","name":"4","category":"B" } ]); self.listA = ko.observableArray([]); self.listB = ko.observableArray([]); for(var i in self.listArr()) { if(self.listArr()[i].category == "A") { self.listA.push(self.listArr()[i]); } else if(self.listArr()[i].category == "B") { self.listB.push(self.listArr()[i]); } } ko.applyBindings(self);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <div>List A</div> <div data-bind="foreach:listA"> <span data-bind= "text : $data.name"></span> <br/> </div> <div>List B</div> <div data-bind="foreach:listB"> <span data-bind= "text : $data.name"></span> <br/> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.