搜索Stack Overflow,我找到了我需要的问题已经回答了。唯一的问题是,这个问题是针对一个价格较低的JQuery自动完成小部件回答的。这个主题在这里:jquery-autocomplete plugin search
本质上,我需要用JQuery自动完成做的是在数据库中找到所有的搜索词,并以任何顺序找到它们。例如,如果我们有一个数据库,如下所示:
var availableTags = [
"apple is good",
"apple grows on tree",
"the tree and the apple",
"red apple",
"apple tree"
];我们搜索“苹果树”,得到的结果是:
“苹果长在树上”,
“树与苹果”,
“苹果树”,
我希望这已经足够清楚了!
发布于 2014-08-08 21:31:38
我建议使用JQueryUI的自动补全功能:http://jqueryui.com/autocomplete/
它很容易使用,而且功能相当强大。我想它可以满足你的需求。
否则,您可以自己创建自己的自动完成功能。为此,只需使用简单的regex:对于每个输入单词,测试是否在源数据中找到单词。如果只有一个匹配项,请将数据附加到结果中。
以下是使用RegExp的JS代码示例:
// Here your tags
var availableTags = [
"apple is good",
"amazing apple"
// ...
];
// The main function
// $target is the input field
function autocomplete($target) {
var outcome;
var words;
var input;
var tmp;
outcome = new Array(); // wraps tags which match autcompletion
words = new Array(); // wraps all words from your input
input = $target.val().trim(); // input value
if (input === '') {
// No words, do nothing
return outcome;
}
// First step: browse input to extract all
// words
tmp = '';
for (var i = 0; i < input.length; i++) {
var current = input[i];
if (current === ' ') {
words.push(tmp);
tmp = '';
} else {
tmp += current;
}
}
// Do no forget pending word
words.push(tmp);
// Second step: browse each checked-in tag
// and test if all provided words are found
// in it
for (var i = 0; i < availableTags.length; i++) {
var isCancelled = false;
var j = 0;
var current = availableTags[i];
while (j < words.length && !isCancelled) {
var r = new RegExp(words[j], 'gi');
if (r.test(current)) {
// Ok word was found, go ahead
j++;
} else {
// Word was not here. You do not
// need to go ahead because you
// want to find all words in
// your tag
isCancelled = true;
}
}
if (!isCancelled) {
// If operation was not cancelled,
// save tag
outcome.push(current);
}
}
return outcome;
}https://stackoverflow.com/questions/25194049
复制相似问题