如何使用Js和Jquery创建精确搜索

时间:2016-07-16 19:31:10

标签: javascript jquery ajax

我试图创建一个扩展搜索,你可以找到人们不仅使用名称,而且还有一些组合...例如我有这个玩家列表,这个代码的安静工作正常,但如果我想要寻找像守门员英格兰这样的功能。这行代码不起作用((val.position.search(myExp)!= -1)||(val.nationality.search(myExp)!= -1))

$("#search").keyup(function() {
    var field = $("#search").val();
    var myExp = new RegExp(field, "i");
    $.getJSON("players.json", function(data) {
      var output = "<ul>";
      $.each(data, function(key, val) {
          if ((val.name.search(myExp) != -1) || (val.position.search(myExp) != -1) || ((val.position.search(myExp) != -1) || (val.nationality.search(myExp) != -1))) {
              output += "<li>";
              output += '<p class="name">' + val.name + '</p>';
              output += '<p>' + val.position + '</p>';
              output += '<p>' + val.dateOfBirth + '</p>';
              output += '<p>' + val.nationality + '</p>';
              output += '<p>' + val.contractUntil + '</p>';
              output += '<p>' + val.marketValue + '</p>';
              output += "</li>";
          }
      });
      output += "</ul>";
      $("#update").html(output);
  });
});

{  
      "id":2138,
      "name":"Thibaut Courtois",
      "position":"Keeper",
      "jerseyNumber":13,
      "dateOfBirth":"1992-05-11",
      "nationality":"Belgium",
      "contractUntil":"2019-06-30",
      "marketValue":"35,000,000 ˆ"
   },
   {  
      "id":2140,
      "name":"Jamal Blackman",
      "position":"Keeper",
      "jerseyNumber":27,
      "dateOfBirth":"1993-10-27",
      "nationality":"England",
      "contractUntil":"2019-06-30",
      "marketValue":"250,000 ˆ"
   },

1 个答案:

答案 0 :(得分:1)

您必须执行多个搜索查询,因为您的查询中有多个单词:
&#34;英格兰守门员&#34; =&GT; &#34;英格兰&#34;和#34;守门员&#34;

所以你想通过&#34; england&#34;来过滤这些项目。以及#34;守门员&#34; ..

最好的方法是创建一个小函数,每个函数都会执行一部分:

// Note: this function returns the filter function
var myFilter = function(regex) {
  return function(item) {
    return regex.test(item.name)
      || regex.test(item.position)
      || regex.test(item.nationality)
  }
}

// this is a higher order function, takes the items and the full searchString as arguments
var findMatches = function(items, searchString) {
  // make a copy of the items / data
  var found = items.slice(0, item.length);

  // split the searchString, and filter the items by it
  searchString.split(' ').forEach(function(part) {
    found = found.filter(myFilter(new RegEx(part, 'i'))
  });

  return found;
}

现在您可以在代码中使用它:

...
var output = "<ul>";
var filteredData = findMatches(data, field);
$.each(filteredData, function(key, val) {
   // filteredData should be fine, you can just render it
}
...