using knockout to make display = none ? - search

2019-08-29 02:06发布

问题:

I am using knockout to filter through a list and find the right list element my problem is: when I find this element how can I make it the first element and hide other list elments? this is my JS:

var myViewModel = {

items: ko.observableArray(),
title: ko.observable('title'),
url: ko.observable('index.HTML'),
query: ko.observable(''),


 items.toLowerCase().indexOf(myViewModel.filterKeyword().toLowerCase()) !== 
   -1;


search: function(value) {
    for (var i = 0; i < myViewModel.items().length ; i++) {
       if (myViewModel.items()[i].toLowerCase().indexOf(value.toLowerCase()) 
      >= 0 )       {
           // this is the elemnt you are searching for ..
           console.log(myViewModel.items()[i]);
      }
      }
       }
         };

this is my HTML :

<input placeholder="Search…" type="search" data-bind="value: query, valueUpdate: 'keyup'" autocomplete="off">
  <ul id="myUL" data-bind="foreach: items">
            <li>
              <a onclick="log(this)" data-bind="visible: true, text: $data">
           </a>
            </li>
          </ul>

this is my console when I search for an elment ()

here some link I found, here my problem with this is that it removes the array and then loop ! that not allowed since there is no element to loop!

回答1:

Make a computed that filters the list and use that in your ul data-bind.

var myViewModel = {

  items: ko.observableArray(['one', 'two', 'three']),
  title: ko.observable('title'),
  url: ko.observable('index.HTML'),
  query: ko.observable(''),
  filteredItems: ko.pureComputed(function () {
    return myViewModel.items().filter((i) =>
      i.toLowerCase().indexOf(myViewModel.query().toLowerCase()) >= 0
    );
  })
};

ko.applyBindings(myViewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input placeholder="Search…" type="search" data-bind="value: query, valueUpdate: 'keyup'" autocomplete="off">
<ul id="myUL" data-bind="foreach: filteredItems">
  <li>
    <a onclick="log(this)" data-bind="visible: true, text: $data">
    </a>
  </li>
</ul>