jQuery UI 自动完成 v1.8.14 多词搜索 +突出显示

发布于 2024-11-30 19:38:38 字数 435 浏览 1 评论 0原文

我正在尝试使用 jQuery UI Autocomplete v1.8.14 实现两件事。

1) 对所有匹配项使用空格分隔的单词搜索(与顺序无关): (例如搜索“some heart”,匹配“赢得某人的心”)

2) 突出显示所有匹配项: (例如搜索“some heart”,匹配“赢得some one的heart”)

此问题已被多次询问,但我一直无法找到显示正确实现的简单、可重现的代码。

我已经启动了 JS Fiddle:http://jsfiddle.net/KywMH/2/。如果可能,请以可重现代码的形式回答。

谢谢。

I'm trying to achieve two things using jQuery UI Autocomplete v1.8.14.

1) Use a space delimited word search for all matches (independent of order):
(eg search "some heart", matches "win the heart of someone")

2) Highlight all of the matches:
(eg search "some heart", matches "win the heart of some one")

This question has been asked multiple times, but I have been unable to find simple, reproducible code showing correct implementation.

I've started a JS Fiddle: http://jsfiddle.net/KywMH/2/. If possible please answer in the form of reproducible code.

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

锦上情书 2024-12-07 19:38:38

这是一种方法:在 jsFiddle 上查看它的实际情况。

var availableTags = [
    "win the day",
    "win the heart of",
    "win the heart of someone"
];
var autoCompNodeId  = 'tags';

$( "#" + autoCompNodeId ).autocomplete ( {
    source: function (requestObj, responseFunc) {
                var matchArry   = availableTags.slice (); //-- Copy the array
                var srchTerms   = $.trim (requestObj.term).split (/\s+/);

                //--- For each search term, remove non-matches.
                $.each (srchTerms, function (J, term) {
                    var regX    = new RegExp (term, "i");
                    matchArry   = $.map (matchArry, function (item) {
                        return regX.test (item)  ?  item  : null;
                    } );
                } );

                //--- Return the match results.
                responseFunc (matchArry);
            },

    open:   function (event, ui) {
                /*--- This function provides no hooks to the results list, so we have to trust the
                    selector, for now.
                */
                var resultsList = $("ul.ui-autocomplete > li.ui-menu-item > a");
                var srchTerm    = $.trim ( $("#" + autoCompNodeId).val () ).split (/\s+/).join ('|');

                //--- Loop through the results list and highlight the terms.
                resultsList.each ( function () {
                    var jThis   = $(this);
                    var regX    = new RegExp ('(' + srchTerm + ')', "ig");
                    var oldTxt  = jThis.text ();

                    jThis.html (oldTxt.replace (regX, '<span class="srchHilite">$1</span>') );
                } );
            }
} );

由于旧的高亮功能不再可用,我们使用 open事件来突出显示搜索词。特别注意不要突出显示内部标签。

Here's one way: See it in action at jsFiddle.

var availableTags = [
    "win the day",
    "win the heart of",
    "win the heart of someone"
];
var autoCompNodeId  = 'tags';

$( "#" + autoCompNodeId ).autocomplete ( {
    source: function (requestObj, responseFunc) {
                var matchArry   = availableTags.slice (); //-- Copy the array
                var srchTerms   = $.trim (requestObj.term).split (/\s+/);

                //--- For each search term, remove non-matches.
                $.each (srchTerms, function (J, term) {
                    var regX    = new RegExp (term, "i");
                    matchArry   = $.map (matchArry, function (item) {
                        return regX.test (item)  ?  item  : null;
                    } );
                } );

                //--- Return the match results.
                responseFunc (matchArry);
            },

    open:   function (event, ui) {
                /*--- This function provides no hooks to the results list, so we have to trust the
                    selector, for now.
                */
                var resultsList = $("ul.ui-autocomplete > li.ui-menu-item > a");
                var srchTerm    = $.trim ( $("#" + autoCompNodeId).val () ).split (/\s+/).join ('|');

                //--- Loop through the results list and highlight the terms.
                resultsList.each ( function () {
                    var jThis   = $(this);
                    var regX    = new RegExp ('(' + srchTerm + ')', "ig");
                    var oldTxt  = jThis.text ();

                    jThis.html (oldTxt.replace (regX, '<span class="srchHilite">$1</span>') );
                } );
            }
} );

Because the old highlight function is no longer available, we use the open event to highlight the search terms. Pay special attention not to highlight inside tags.

番薯 2024-12-07 19:38:38

下面的解决方案通过

1) 修改自动完成源函数

2) 修改 .data('autocomplete')._renderItem

解决这两个问题可以在此处找到工作的 JS Fiddle: http://jsfiddle.net/W8MKt/7/

对代码或解决方案的任何批评将不胜感激。

谢谢。

<div class="ui-widget">
<label for="tags">Multi-word search: </label>
<input id="tags">
</div>

$(function() {
    var availableTags = [
        "win the day",
        "win the heart of",
        "win the heart of someone"
    ];

    $( "#tags" ).autocomplete({
        source: function(request, response) {

            var aryResponse = [];
            var arySplitRequest = request.term.split(" ");

            for( i = 0; i < availableTags.length; i++ ) {

                var intCount = 0;
                for( j = 0; j < arySplitRequest.length; j++ ) {

                    regexp = new RegExp(arySplitRequest[j]);

                    var test = availableTags[i].match(regexp);

                    if( test ) {

                        intCount++;

                    } else if( !test ) {

                    intCount = arySplitRequest.length + 1;

                    }

                    if ( intCount == arySplitRequest.length ) {

                        aryResponse.push( availableTags[i] );

                    }
                };
            }

            response(aryResponse);

        }

    }).data('autocomplete')._renderItem = function( ul, item ) {

        var srchTerm = $.trim(this.term).split(/\s+/).join ('|');

        var strNewLabel = item.label;

            regexp = new RegExp ('(' + srchTerm + ')', "ig");

            var strNewLabel = strNewLabel.replace(regexp,"<span style='font-weight:bold;color:Blue;'>$1</span>");

      return $( "<li></li>" )
          .data( "item.autocomplete", item )
          .append( "<a>" + strNewLabel + "</a>" )
          .appendTo( ul );

   };

});

The solution below solves these two problems by

1) Modifying the autocomplete source function

2) Modifying .data('autocomplete')._renderItem

A working JS Fiddle can be found here: http://jsfiddle.net/W8MKt/7/

Any critique of the code or the solution would be appreciated.

Thank you.

<div class="ui-widget">
<label for="tags">Multi-word search: </label>
<input id="tags">
</div>

$(function() {
    var availableTags = [
        "win the day",
        "win the heart of",
        "win the heart of someone"
    ];

    $( "#tags" ).autocomplete({
        source: function(request, response) {

            var aryResponse = [];
            var arySplitRequest = request.term.split(" ");

            for( i = 0; i < availableTags.length; i++ ) {

                var intCount = 0;
                for( j = 0; j < arySplitRequest.length; j++ ) {

                    regexp = new RegExp(arySplitRequest[j]);

                    var test = availableTags[i].match(regexp);

                    if( test ) {

                        intCount++;

                    } else if( !test ) {

                    intCount = arySplitRequest.length + 1;

                    }

                    if ( intCount == arySplitRequest.length ) {

                        aryResponse.push( availableTags[i] );

                    }
                };
            }

            response(aryResponse);

        }

    }).data('autocomplete')._renderItem = function( ul, item ) {

        var srchTerm = $.trim(this.term).split(/\s+/).join ('|');

        var strNewLabel = item.label;

            regexp = new RegExp ('(' + srchTerm + ')', "ig");

            var strNewLabel = strNewLabel.replace(regexp,"<span style='font-weight:bold;color:Blue;'>$1</span>");

      return $( "<li></li>" )
          .data( "item.autocomplete", item )
          .append( "<a>" + strNewLabel + "</a>" )
          .appendTo( ul );

   };

});
锦上情书 2024-12-07 19:38:38

我发现使用内置的自动完成过滤器来减少搜索空间也能达到目的(而且更简单):

source: function( request, response ) {
    var searchspace = availableTags;
    // split by space or however you want to split up your search phrase into terms
    var searchwords = request.term.split(" ");

    $.each(searchwords, function() {
        searchspace = $.ui.autocomplete.filter(searchspace, this);
    });

    // in case you don't want to return the whole thing, if your searchspace is large
    var mySlice = searchspace.slice(0, 10);
        response(mySlice);
    },
}

I've found that using the built in autocomplete filter to reduce your search space does the trick as well (and is much simpler):

source: function( request, response ) {
    var searchspace = availableTags;
    // split by space or however you want to split up your search phrase into terms
    var searchwords = request.term.split(" ");

    $.each(searchwords, function() {
        searchspace = $.ui.autocomplete.filter(searchspace, this);
    });

    // in case you don't want to return the whole thing, if your searchspace is large
    var mySlice = searchspace.slice(0, 10);
        response(mySlice);
    },
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文