jqueryui自动完成如何传入一组关键字来搜索每个对象?

时间:2012-01-26 12:11:01

标签: javascript jquery jquery-ui autocomplete filtering

我正在尝试使用jQueryUI自动完成功能为我网站中的各种功能页面实现网站快速搜索功能。因此,当他们搜索“创建”时,将显示“创建用户”选项和“创建组织”选项。当他们搜索“创建你”时,它只会显示“创建用户”选项。这些只是一些链接。但正如您所看到的,每个页面都会有一些不同的关键字/同义词,它们都指向同一页面。

基本上我想要一个像这样的结构:

var links = [   
{
    keywords: ['create', 'add', 'make', 'insert', 'user'],
    label: "Create user",
    desc: "Create a user in the system",
    url: 'http://mysite.com/user/create/'
},
{
    keywords: ['create', 'add', 'make', 'insert', 'organisation'],
    label: "Create organisation",
    desc: "Create an organisation in the system",
    url: 'http://mysite.com/organisation/create/'
}];

因此,当他们输入时,它应该查找链接数组,然后搜索关键字数组,根据他们输入的内容搜索部分文本匹配。如果找到一个,那么它将在自动中显示该条目完成者。但是,如果第二个或第三个搜索词与任何关键词都不匹配,那么它就不会显示它。

现在我听说你可以通过提供源作为回调来做到这一点吗?

到目前为止,这是我的代码(编辑:使用工作解决方案更新):

        var links = [
        {
            keywords: ['create', 'add', 'make', 'insert', 'user'],
            label: "Create user",
            desc: "Create a user in the system",
            url: 'http://mysite.com/user/create/'
        },
        {
            keywords: ['create', 'add', 'make', 'insert', 'organisation'],
            label: "Create organisation",
            desc: "Create an organisation in the system",
            url: 'http://mysite.com/organisation/create/'
        }];

        $("#searchTerms").autocomplete(
        {
            minLength: 2,               
            source: function(request, response)
            {
                var matched = [];

                // Get entered search terms (request.term) from user and search through all links keywords
                for (var k = 0; k < links.length; k++)
                {
                    // If it matches, push the object into a new array
                    if (checkSearchWordsMatchKeywords(request.term, links[k]['keywords']))
                    {
                        matched.push(links[k]);
                    }
                }

                // Display the filtered results
                response(matched);
            },
            focus: function( event, ui )
            {
                $( "#searchTerms" ).val( ui.item.label );
                return false;
            },
            select: function( event, ui )
            {
                // Redirect to the url
                $( "#searchTerms" ).val( ui.item.label );
                window.location.replace(ui.item.url);

                return false;
            }
        })
        .data( "autocomplete" )._renderItem = function( ul, item ) {
            return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( '<a href=""><b>' + item.label + '</b><br>' + item.desc + '</a>' )
                .appendTo( ul );
        };


        /**
         * Check that each word in a search string matches at least one keyword in an array
         * E.g. searchWords = 'create use'  and  keywords = ['create', 'add', 'make', 'insert', 'user'] will return true
         */
        function checkSearchWordsMatchKeywords(searchWords, keywords)
        {
            var searchWords = searchWords.toLowerCase();    // Lowercase the search words
            var searchWords = searchWords.split(' ');       // Break up the search into separate words
            var numOfSearchWords = searchWords.length;      // Count number of search words
            var numOfKeywords = keywords.length;            // Count the number of keywords
            var matches = [];                               // Will contain the keywords that matched the search words

            // For each search word look up the keywords array to see if the search word partially matches the keyword
            for (var i = 0; i < numOfSearchWords; i++)
            {
                // For each keyword
                for (var j = 0; j < numOfKeywords; j++)
                {   
                    // Check search word is part of a keyword
                    if (keywords[j].indexOf(searchWords[i]) != -1)
                    {
                        // Found match, store match, then look for next search word
                        matches.push(keywords[j]);
                        break;
                    }
                }
            }

            // Count the number of matches, and if it equals the number of search words then the search words match the keywords
            if (matches.length == numOfSearchWords)
            {
                return true;
            }

            return false;
        }
    });

好的,所以checkSearchWordsMatchKeywords函数最后肯定有效,因为我已经测试过了。什么是行不通的是我不知道我应该从jQueryUI搜索中返回什么:function。

请帮忙吗?

1 个答案:

答案 0 :(得分:1)

我在工作中遇到了这个问题。为了解决这个问题,我们创建了自己的搜索功能。即使它们在您想要显示的实际字符串中,也要搜索keywords

$( "#searchTerms" ).autocomplete({
   search: function(event, ui) {  
      // Add your super search function here
   }
});