gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 22:46:00 28 4
gpt4 key购买 nike

我正在尝试创建一个扩展搜索,您不仅可以找到使用这些名称的人,还可以找到一些组合...例如,我有这个玩家列表,并且这种和平的代码工作正常,但如果我想找到对于像这样的特征——英格兰门将。这行代码不起作用 ((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 ˆ"
},

最佳答案

您必须执行多个搜索查询,因为您的查询中有多个单词:
“英格兰守门员”=>“英格兰”和“守门员”

因此您想按“英格兰”和“守门员”过滤项目..

最好是创建一个小函数,每个函数都会完成其中的一部分:

// 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
}
...

关于javascript - 如何使用 Js 和 Jquery 创建精确搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38414847/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com