オートコンプリート プラグインの結果をカスタム形式にするにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/2435964

質問

私が使用しているのは、 jQuery UI オートコンプリート プラグイン. 。ドロップダウン結果で検索文字列を強調表示する方法はありますか?

たとえば、データとして「foo bar」があり、「foo」と入力すると、「ふー 次のように、ドロップダウンで「バー」を選択します。

“Breakfast” appears after “Bre” is typed with “Bre” having a bold type and “akfast” having a light one.

役に立ちましたか?

解決

Autocomplete with live suggestion

はい、モンキーパッチをオートコンプリートすれば可能です。

jQuery UI の v1.8rc3 に含まれるオートコンプリート ウィジェットでは、オートコンプリート ウィジェットの _renderMenu 関数内で候補のポップアップが作成されます。この関数は次のように定義されます。

_renderMenu: function( ul, items ) {
    var self = this;
    $.each( items, function( index, item ) {
        self._renderItem( ul, item );
    });
},

_renderItem 関数は次のように定義されます。

_renderItem: function( ul, item) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<a>" + item.label + "</a>" )
        .appendTo( ul );
},

したがって、必要なのは、その _renderItem fn を、目的の効果を生み出す独自の作成物に置き換えることです。私が学んだ、ライブラリ内の内部関数を再定義するこのテクニックは、 モンキーパッチ. 。私がやった方法は次のとおりです。

  function monkeyPatchAutocomplete() {

      // don't really need this, but in case I did, I could store it and chain
      var oldFn = $.ui.autocomplete.prototype._renderItem;

      $.ui.autocomplete.prototype._renderItem = function( ul, item) {
          var re = new RegExp("^" + this.term) ;
          var t = item.label.replace(re,"<span style='font-weight:bold;color:Blue;'>" + 
                  this.term + 
                  "</span>");
          return $( "<li></li>" )
              .data( "item.autocomplete", item )
              .append( "<a>" + t + "</a>" )
              .appendTo( ul );
      };
  }

その関数を 1 回呼び出す $(document).ready(...) .

さて、これはハックです。理由は次のとおりです。

  • リスト内に表示されるすべての項目に対して正規表現オブジェクトが作成されます。その正規表現オブジェクトはすべての項目で再利用する必要があります。

  • 完成したパーツの書式設定に使用される CSS クラスはありません。インラインスタイルです。
    これは、同じページに複数のオートコンプリートがある場合、それらはすべて同じ処理を受けることを意味します。CSS スタイルがそれを解決します。

...しかし、これは主なテクニックを示しており、基本的な要件には機能します。

alt text

更新された動作例: http://output.jsbin.com/qixaxinuhe


入力された文字の大文字と小文字を使用するのではなく、一致文字列の大文字と小文字を保持するには、次の行を使用します。

var t = item.label.replace(re,"<span style='font-weight:bold;color:Blue;'>" + 
          "$&" + 
          "</span>");

言い換えれば、上記の元のコードから始めて、次のように置き換えるだけです。 this.term"$&".


編集
上記の変更点 ページ上のオートコンプリート ウィジェット。1 つだけを変更したい場合は、この質問を参照してください。
ページ上のオートコンプリートの * 1 つの* インスタンスにパッチを適用するにはどうすればよいですか?

他のヒント

これも機能します:

       $.ui.autocomplete.prototype._renderItem = function (ul, item) {
            item.label = item.label.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
            return $("<li></li>")
                    .data("item.autocomplete", item)
                    .append("<a>" + item.label + "</a>")
                    .appendTo(ul);
        };

@Jörn Zaefferer と @Cheeso の回答を組み合わせたものです。

とても助かりました。ありがとう。+1。

以下は、「文字列は用語で始まる必要がある」に基づいて並べ替えた軽量バージョンです。

function hackAutocomplete(){

    $.extend($.ui.autocomplete, {
        filter: function(array, term){
            var matcher = new RegExp("^" + term, "i");

            return $.grep(array, function(value){
                return matcher.test(value.label || value.value || value);
            });
        }
    });
}

hackAutocomplete();

jQueryUI 1.9.0 では、_renderItem の動作方法が変更されます。

以下のコードは、この変更を考慮しており、Jörn Zaefferer の jQuery Autocomplete プラグインを使用してハイライト マッチングを行っている方法も示しています。検索語全体内の個々の語句がすべて強調表示されます。

Knockout と jqAuto の使用に移行して以来、これが結果のスタイルを設定するはるかに簡単な方法であることがわかりました。

function monkeyPatchAutocomplete() {
   $.ui.autocomplete.prototype._renderItem = function (ul, item) {

      // Escape any regex syntax inside this.term
      var cleanTerm = this.term.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

      // Build pipe separated string of terms to highlight
      var keywords = $.trim(cleanTerm).replace('  ', ' ').split(' ').join('|');

      // Get the new label text to use with matched terms wrapped
      // in a span tag with a class to do the highlighting
      var re = new RegExp("(" + keywords + ")", "gi");
      var output = item.label.replace(re,  
         '<span class="ui-menu-item-highlight">$1</span>');

      return $("<li>")
         .append($("<a>").html(output))
         .appendTo(ul);
   };
};

$(function () {
   monkeyPatchAutocomplete();
});

機能的な完全な例を次に示します。

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Autocomplete - jQuery</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css">
</head>
<body>
<form id="form1" name="form1" method="post" action="">
  <label for="search"></label>
  <input type="text" name="search" id="search" />
</form>

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script>
$(function(){

$.ui.autocomplete.prototype._renderItem = function (ul, item) {
    item.label = item.label.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
    return $("<li></li>")
            .data("item.autocomplete", item)
            .append("<a>" + item.label + "</a>")
            .appendTo(ul);
};


var availableTags = [
    "JavaScript",
    "ActionScript",
    "C++",
    "Delphi",
    "Cobol",
    "Java",
    "Ruby",
    "Python",
    "Perl",
    "Groove",
    "Lisp",
    "Pascal",
    "Assembly",
    "Cliper",
];

$('#search').autocomplete({
    source: availableTags,
    minLength: 3
});


});
</script>
</body>
</html>

お役に立てれば

さらに簡単な方法として、これを試してください。

$('ul: li: a[class=ui-corner-all]').each (function (){      
 //grab each text value 
 var text1 = $(this).text();     
 //grab user input from the search box
 var val = $('#s').val()
     //convert 
 re = new RegExp(val, "ig") 
 //match with the converted value
 matchNew = text1.match(re);
 //Find the reg expression, replace it with blue coloring/
 text = text1.replace(matchNew, ("<span style='font-weight:bold;color:green;'>")  + matchNew +    ("</span>"));

    $(this).html(text)
});
  }

これは Ted de Koning のソリューションの焼き直しです。これには以下が含まれます:

  • 大文字と小文字を区別しない検索
  • 検索された文字列が多数出現する場合の検索
$.ui.autocomplete.prototype._renderItem = function (ul, item) {

    var sNeedle     = item.label;
    var iTermLength = this.term.length; 
    var tStrPos     = new Array();      //Positions of this.term in string
    var iPointer    = 0;
    var sOutput     = '';

    //Change style here
    var sPrefix     = '<strong style="color:#3399FF">';
    var sSuffix     = '</strong>';

    //Find all occurences positions
    tTemp = item.label.toLowerCase().split(this.term.toLowerCase());
    var CharCount = 0;
    tTemp[-1] = '';
    for(i=0;i<tTemp.length;i++){
        CharCount += tTemp[i-1].length;
        tStrPos[i] = CharCount + (i * iTermLength) + tTemp[i].length
    }

    //Apply style
    i=0;
    if(tStrPos.length > 0){
        while(iPointer < sNeedle.length){
            if(i<=tStrPos.length){
                //Needle
                if(iPointer == tStrPos[i]){
                    sOutput += sPrefix + sNeedle.substring(iPointer, iPointer + iTermLength) + sSuffix;
                    iPointer += iTermLength;
                    i++;
                }
                else{
                    sOutput += sNeedle.substring(iPointer, tStrPos[i]);
                    iPointer = tStrPos[i];
                }
            }
        }
    }


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

これは、正規表現を必要とせず、ラベル内の複数の結果と一致するバージョンです。

$.ui.autocomplete.prototype._renderItem = function (ul, item) {
            var highlighted = item.label.split(this.term).join('<strong>' + this.term +  '</strong>');
            return $("<li></li>")
                .data("item.autocomplete", item)
                .append("<a>" + highlighted + "</a>")
                .appendTo(ul);
};

コンボボックスのデモを見てください。結果の強調表示が含まれています。 http://jqueryui.com/demos/autocomplete/#combobox

そこで使用されている正規表現は、HTML の結果も処理します。

私のバージョンは次のとおりです。

  • RegEx の代わりに DOM 関数を使用して文字列を分割したり、span タグを挿入したりする
  • すべてではなく、指定されたオートコンプリートのみが影響を受けます
  • UI バージョン 1.9.x で動作します
function highlightText(text, $node) {
    var searchText = $.trim(text).toLowerCase(),
        currentNode = $node.get(0).firstChild,
        matchIndex,
        newTextNode,
        newSpanNode;
    while ((matchIndex = currentNode.data.toLowerCase().indexOf(searchText)) >= 0) {
        newTextNode = currentNode.splitText(matchIndex);
        currentNode = newTextNode.splitText(searchText.length);
        newSpanNode = document.createElement("span");
        newSpanNode.className = "highlight";
        currentNode.parentNode.insertBefore(newSpanNode, currentNode);
        newSpanNode.appendChild(newTextNode);
    }
}
$("#autocomplete").autocomplete({
    source: data
}).data("ui-autocomplete")._renderItem = function (ul, item) {
    var $a = $("<a></a>").text(item.label);
    highlightText(this.term, $a);
    return $("<li></li>").append($a).appendTo(ul);
};

一致したテキストを強調表示する例

次のコードを使用できます。

ライブラリ:

$.widget("custom.highlightedautocomplete", $.ui.autocomplete, {
    _renderItem: function (ul, item) {
        var $li = $.ui.autocomplete.prototype._renderItem.call(this,ul,item);
        //any manipulation with li
        return $li;
    }
});

そしてロジック:

$('selector').highlightedautocomplete({...});

オーバーライドできるカスタム ウィジェットを作成します _renderItem 上書きせずに _renderItem オリジナルのプラグインのプロトタイプ。

私の例では、コードを簡素化するためにオリジナルのレンダリング関数も使用しました

これは、オートコンプリートの異なるビューを使用してさまざまな場所でプラグインを使用し、コードを壊したくない場合に重要です。

代わりにサードパーティのプラグインを使用する場合は、ハイライト オプションがあります。http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions

(「オプション」タブを参照)

複数の値をサポートするには、次の関数を追加するだけです。

function getLastTerm( term ) {
  return split( term ).pop();
}

var t = String(item.value).replace(new RegExp(getLastTerm(this.term), "gi"), "<span class='ui-state-highlight'>$&</span>");
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top