更新一个JQuery自动完成问题

Update a JQuery autocomplete issue

本文关键字:成问题 JQuery 一个 更新      更新时间:2023-09-26

通过Stack Overflow搜索,我发现我需要的确切问题已经得到了回答。唯一的问题是它回答了一个被贬低的JQuery自动完成小部件。jquery-autocomplete插件搜索

本质上,我需要用JQuery Autocomplete做的是在数据库中找到所有的搜索词,并以任何顺序找到它们。例如,如果我们有一个像这样的数据库:

var availableTags = [  
  "apple is good",  
  "apple grows on tree",  
  "the tree and the apple",  
  "red apple",  
  "apple tree"  
];

我们搜索"apple tree",我们会得到这个:

"苹果长在树上",
《树和苹果》,
"苹果树",

我希望这足够清楚!

我建议使用JQueryUI的自动补全功能:http://jqueryui.com/autocomplete/

它很容易使用和相当强大。我想它能满足你的需要。

否则,你可以自己创建你自己的自动完成功能。为此,只需使用简单的正则表达式:对于每个输入单词,测试是否在源数据中找到单词。如果只有一个匹配项,则将数据附加到结果中。

下面是使用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;
}