创建搜索栏

时间:2016-02-21 06:55:25

标签: javascript jquery

我正在尝试制作一个纯JavaScript搜索框。我希望它能够非常松散地搜索,即它不应该区分大小写,不应考虑空格等等。

我遇到了this codepen,它有我正在寻找的东西,但它是用JQuery编写的。我正在尝试将其转换为JavaScript,但我无法做到这一点。

我的问题不在于动画,而是在最低限度的搜索代码上。所以基本上这里是我需要帮助的唯一部分:

import UIKit

class SubtitleCell: UITableViewCell {

    override init(style style: UITableViewCellStyle, reuseIdentifier reuseIdentifier: String?) {
        super.init(style: .Subtitle reuseIdentifier: reuseIdentifier)
    }
}

我得到的JavaScript等同于JQuery的tableView.registerClass(SubtitleCell.self, forCellReuseIdentifier: "cell") ,它位于JSFiddle下面。

JSFiddle

$.extend($.expr[':'], {
    'containsi': function(elem, i, match, array) {
        return (elem.textContent || elem.innerText || '').toLowerCase()
            .indexOf((match[3] || "").toLowerCase()) >= 0;
    }
});

var searchSplit = searchTerm.replace(/ /g, "'):containsi('")

$("#list li").not(":containsi('" + searchSplit + "')").each(function(e) {
    $(this).addClass('hidden');

});
$("#list li:containsi('" + searchSplit + "')").each(function(e) {
    $(this).removeClass('hidden');

});
extend
$(document).ready(function() {


  // My JavaScript code

  var input = document.getElementById('search-text');
  input.addEventListener("keyup", function() {
    var searchTerm = input.value,
      listItem = document.getElementsByClassName('searchArray');

    // JavaScript equivalent of jQuery's extend method
    function extend(a, b) {
      for (var key in b)
        if (b.hasOwnProperty(key))
          a[key] = b[key];
      return a;
    }
  });



  // Bare minimum code from http://codepen.io/robooneus/pen/ivdFH	

  //we want this function to fire whenever the user types in the search-box
  $("#search-text").keyup(function() {

    //first we create a variable for the value from the search-box
    var searchTerm = $("#search-text").val();

    //then a variable for the list-items (to keep things clean)
    var listItem = $('#list').children('li');

    //extends the default :contains functionality to be case insensitive
    //if you want case sensitive search, just remove this next chunk
    $.extend($.expr[':'], {
      'containsi': function(elem, i, match, array) {
        return (elem.textContent || elem.innerText || '').toLowerCase()
          .indexOf((match[3] || "").toLowerCase()) >= 0;
      }
    }); //end of case insensitive chunk


    //this part is optional
    //here we are replacing the spaces with another :contains
    //what this does is to make the search less exact by searching all words and not full strings
    var searchSplit = searchTerm.replace(/ /g, "'):containsi('")


    //here is the meat. We are searching the list based on the search terms
    $("#list li").not(":containsi('" + searchSplit + "')").each(function(e) {

      //add a "hidden" class that will remove the item from the list
      $(this).addClass('hidden');

    });

    //this does the opposite -- brings items back into view
    $("#list li:containsi('" + searchSplit + "')").each(function(e) {

      //remove the hidden class (reintroduce the item to the list)
      $(this).removeClass('hidden');

    });
  });
});

1 个答案:

答案 0 :(得分:1)

您可以使用typeahead.js substringMatcher功能

的版本

var substringMatcher = function(strs, q, cb) {
  return (function(q, cb, name) {
    var matches, substrRegex;

    // an array that will be populated with substring matches
    matches = [];

    // regex used to determine if a string contains the substring `q`
    substrRegex = new RegExp(q, 'i');

    // iterate through the pool of strings and for any string that
    // contains the substring `q`, add it to the `matches` array
    strs.forEach(function(str, i) {

      if (substrRegex.test(str)) {
        // the typeahead jQuery plugin expects suggestions to a
        // JavaScript object, refer to typeahead docs for more info

        matches.push(name(str));
      }
    });

    cb(matches);
  }(q, cb, function(res) {
    return res
  }));
};

var elems = document.getElementsByClassName('searchArray');
// My JavaScript code
var listItem = Array.prototype.slice.call(elems);

var list = listItem.map(function(el) {
  el.className = el.className + " " + "hidden";
  return el.textContent;
})

var input = document.getElementById('search-text');

input.addEventListener("keyup", function() {
  var searchTerm = this.value;
  if (searchTerm.length === 0) {
    listItem.forEach(function(el, i) {
      el.className = el.className + " " + "hidden"
    });
    return false
  }
  substringMatcher(list, searchTerm, function(results) {
    results.forEach(function(value, index) {
      if (list.indexOf(value) > -1) {
        elems[list.indexOf(value)].className = elems[list.indexOf(value)]
        .className.replace("hidden", "");
      } else {
        listItem.forEach(function(el, i) {
          if (i !== list.indexOf(value)) {
            el.className = el.className + " " + "hidden";
          }
        })
      }
    })
  })

});
.hidden {
  display: none;
}
<input type="text" id="search-text" placeholder="search">
<ul id="list">
  <li class="searchArray">Apple pie</li>
  <li class="searchArray">Pumpkin pie</li>
  <li class="searchArray">Banana-creme pie</li>
  <li class="searchArray">Peach-blackberry cobbler</li>
  <li class="searchArray">Chocolate-strawberry torte</li>
  <li class="searchArray">Chocolate-zucchini cake</li>
  <li class="searchArray">Anything involving chocolate and mint</li>
  <li class="searchArray">Red-velvet cake</li>
  <li class="searchArray">Anything involving fruits that aren't cherries</li>
</ul>