jQuery UI Autocomplete v1.8.14多字搜索+突出显示

时间:2011-08-21 17:35:12

标签: jquery regex jquery-ui jquery-ui-autocomplete

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

1)对所有匹配使用空格分隔词搜索(独立于顺序):      (例如搜索“某些心脏”,匹配“赢得某人的心脏”)

2)突出显示所有比赛:      (例如搜索“某些心脏”,匹配“赢得一些一个心脏

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

我开始了一个JS小提琴:http://jsfiddle.net/KywMH/2/。如果可能,请以可重现的代码形式回答。

谢谢。

3 个答案:

答案 0 :(得分:6)

下面的解决方案通过

解决了这两个问题

1)修改自动完成源功能

2)修改.data('autocomplete')._ renderItem

可以在这里找到一个有效的JS小提琴: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 );

   };

});

答案 1 :(得分:6)

以下是一种方式: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>') );
                } );
            }
} );


由于旧的突出显示功能不再可用,我们使用the open event突出显示搜索字词。请特别注意不要突出显示内部标签。

答案 2 :(得分:4)

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

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);
    },
}