更新JQuery自动完成问题

时间:2014-08-07 23:48:53

标签: javascript jquery autocomplete

通过Stack Overflow搜索,我发现了我需要回答的确切问题。唯一的问题是它是针对一个解压缩的JQuery Autocomplete小部件来回答的。那个主题在这里:jquery-autocomplete plugin search

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

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

我们搜索“苹果树”,我们会得到这个:

“苹果长在树上”,
“树和苹果”,
“苹果树”,

我希望这很清楚!

1 个答案:

答案 0 :(得分:0)

我建议使用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;
}