过滤功能:使用KO挣扎

时间:2016-07-11 11:22:09

标签: javascript jquery html knockout.js

尝试转换此代码:

JS:

self.filter = function() {
    var s = $('#searchField').val();
    console.log(s.toLowerCase().replace(/\b[a-z]/g,"KC"));
    s = s.toLowerCase().replace(/\b[a-z]/g, function(self) {
      console.log(self.toUpperCase());
      return self.toUpperCase();
    });
    $(".locationList > li").each(function() {
      console.log(this);
      $(this).text().search(s) > -1 ? $(this).show() : $(this).hide();
    });
    for(var i = 0; i < self.placeList().length; i++) {
      console.log(self.map);
      self.placeList()[i].marker.setMap(self.placeList()[i].marker.title.search(s) > -1 ? map : null);
    }
  };
};

HTML:

<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
<input id="searchField" data-bind="event: {keyup: filter}" type="text" placeholder='search by name or city' value="">
<hr>
<ul class="locationList" data-bind="foreach: placeList">
  <li>  
    ... 

这样的事情:

的Javascript

self.filterText = ko.observable("");
self.filteredList = ko.computed(function(){
  var filter = self.filterText().toLowerCase();
  return // your filter function. make sure you return an array of what you want! 
}, this);

1 个答案:

答案 0 :(得分:0)

您应该在转发器中使用li-tag上的可见绑定。然后直接隐藏不符合标准的项目。像这样:

<ul data-bind="foreach:placeList">
  <li data-bind="text:$data, visible: filter"></li>
</ul>