循环遍历Javascript数组并显示HTML(淘汰赛)

时间:2016-06-06 06:30:54

标签: javascript arrays knockout.js

我想显示我的模型的JSON数据。这是其中的一个例子:

{"id":"1","name":"1","category":"A" },
{"id":"2","name":"2","category":"B" },
{"id":"3","name":"3","category":"A" },
{"id":"4","name":"4","category":"B" }

我想要的是将javascript变成数组的不同类别我想: A B。

然后在数组匹配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>

这是要走的路吗?我想让东西很容易排序(数组是一个可观察的数组)

1 个答案:

答案 0 :(得分:1)

尝试以下方式: -

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>