jQueryUI 自动完成 - 如何将搜索词与关键字列表匹配并显示匹配的结果? [英] jQueryUI Autocomplete - how to match search words with a list of keywords and show the matched results?

查看:17
本文介绍了jQueryUI 自动完成 - 如何将搜索词与关键字列表匹配并显示匹配的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 jQueryUI 自动完成为我网站中的各种功能页面实现网站快速搜索功能.我猜你可以说它就像 Google Instant Search,但它正在为我网站上的页面编制索引.

I'm trying to use jQueryUI Autocomplete to implement a site quick searching feature for various functionality pages in my site. I guess you could say it is like Google Instant Search but it's indexing pages on my site.

因此,当他们搜索创建"时,它会显示创建用户"选项和创建组织"选项.当他们搜索创建使用"时,它只会显示创建用户"选项.然后他们可以点击结果,它会加载那个页面.这些只是一些链接.但是正如您所看到的,每个页面都会有一些指向同一页面的各种关键字/同义词.

So when they search for "create" it will bring up the Create user option and the Create organisation option. When they search for "create use" it will only show the Create User option. Then they can click on the results and it will load up that page. These are just some of the links. But as you can see, each page will have some various keywords/synonyms that would all point to the same page.

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

Ok so the checkSearchWordsMatchKeywords function at the end there definitely works because I've tested it. What isn't working is I don't know what I'm supposed to return from the jQueryUI search: function.

此外,如果您知道如何优化 checkSearchWordsMatchKeywords() 函数,那么我全神贯注.:)

Also if you know how to optimise that checkSearchWordsMatchKeywords() function then I'm all ears. :)

更新了以下工作解决方案(适用于 jQueryUI 1.9.x):

updated with working solution below (works with jQueryUI 1.9.x):

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 = [];
        var numOfLinks = links.length;

        // Get entered search terms (request.term) from user and search through all links keywords
        for (var k = 0; k < numOfLinks; 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)
    {
        // When the item is selected, put the label text into the search box
        $('#searchTerms').val(ui.item.label);
        return false;
    },
    select: function(event, ui)
    {
        // Put the selected link's label in the text box and redirect to the url
        $('#searchTerms').val(ui.item.label);

        // Redirect to the page using .href so the previous page is saved into the user's browser history
        window.location.href = ui.item.url;
        return false;
    }
})
.data('autocomplete')._renderItem = function(ul, item)
{
    // Show a description underneath the link label. Using the hyperlink here too so that mouse click still works
    return $('<li></li>')
        .data('item.autocomplete', item )
        .append('<a href="' + item.url + '"><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(searchString, keywords)
{
    var searchWords = searchString.toLowerCase().split(' ');    // Lowercase the search words & 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;
}

跳转到页面

推荐答案

我不认为搜索"事件是做您所追求的事情的地方.您应该将 source 选项实现为回调:

I don't the "search" event is the place to do what you're after. You should rather implement the source option as a callback:

$("#searchTerms").autocomplete({
    ...
    source: function(request, response) {        
        var matched = [];
        // Search "request.term" through all links keywords
        for (var k = 0; k < links.length; k++) {
            if (checkSearchWordsMatchKeywords(request.term, links[k]['keywords'])) {
                matched.push(links[k]);
            }
        }
        // display the filtered results
        response(matched);
    }
});

  • request 对象包含 term 属性,它是在输入中输入的文本
  • response 参数是您应该调用以显示结果的回调.
    • the request object contains the term property which is the text that is entered in the input
    • the response parameter is callback that you should call to display the results.
    • 基本上,您获取并过滤数据,然后将其传递给 response() 以显示菜单.

      So basically, you get and filter your data, and pass it to response() to display the menu.

      这篇关于jQueryUI 自动完成 - 如何将搜索词与关键字列表匹配并显示匹配的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆