gpt4 book ai didi

jQuery UI 自动搜索搜索多个字符串

转载 作者:行者123 更新时间:2023-12-01 04:59:52 26 4
gpt4 key购买 nike

我需要向 jQuery UI 自动搜索功能添加一些功能。我想解决的问题是允许用户以任意顺序输入文本,以搜索术语列表并显示建议。例如,假设我有以下术语:

the brown cow jumped over the moon
the blue cow watched in horror
the red cow simply laughed
the green cow got sick at such a sight
the yellow cow lost 5 bucks to the black cow
the black cow smiled at his fortune

If the user types in "the cow", I would expect the autocomplete feature to list all the results.
If I type in "brown moon", I would expect the first result to appear.
If I type in "fortune smiled", the last result would appear.

基本上,此行为允许用户以任何顺序键入任何字符串并获取搜索结果。

这就是我的想法。我需要在“打开”或“搜索”事件中添加回调函数并操纵那里的结果。到目前为止,这是我的代码:

$(function ()
{
var data =
[
"the brown cow jumped over the moon",
"the blue cow watched in horror",
"the red cow simply laughed ",
"the green cow got sick at such a sight",
"the yellow cow lost 5 bucks to the black cow",
"the black cow smiled at his fortune"
];

$(".text-search").autocomplete(
{
autoFocus: true,
source: data,
delay: 0,
minLength: 2,
open: function (e, ui)
{
debugger;
// what should i do here?
},
search: function (e, ui)
{
debugger;
// what should i do here?
}
});
});

<div class="ui-widget">
<label for="autocomplete">Autocomplete: </label>
<input class="text-search">
</div>

最佳答案

我将根据用户输入的文本创建您自己的正则表达式。然后,您可以使用此正则表达式来测试候选列表中的每个项目:

$(".text-search").autocomplete({
autoFocus: true,
source: function(request, response) {
var regexStr = "\\b(" + $.map($.trim(request.term).split(" "), function(term) {
return $.ui.autocomplete.escapeRegex($.trim(term))
}).join("|") + ")\\b",
matcher = new RegExp(regexStr);

response($.grep(data, function(value) {
return matcher.test(value.label || value.value || value);
}));
},
delay: 0,
minLength: 2
});

正则表达式部分看起来很神秘,但它只是使用交替(|)生成一个表达式。例如,如果您输入 brownow,则会生成 \b(brown|cow)\b,它将与任何包含“brown”或“cow”的字符串匹配。

示例: http://jsfiddle.net/hTfj9/

关于jQuery UI 自动搜索搜索多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11148055/

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