Foi útil?

Solução

 Autocomplete com a sugestão ao vivo

Sim, você pode se você macaco-patch autocomplete.

No autocomplete Widget incluído no v1.8rc3 de jQuery UI, o pop-up de sugestões é criada na função _renderMenu do widget autocomplete. Esta função é definida como este:

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

A função _renderItem é definido assim:

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

Então, o que você precisa fazer é substituir o _renderItem fn com a sua própria criação que produz o efeito desejado. Esta técnica, redefinindo uma função interna em uma biblioteca, eu vim para aprender é chamado monkey-patching . Aqui está como eu fiz isso:

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

chamar essa função uma vez em $(document).ready(...).

Agora, este é um truque, porque:

  • há um obj regexp criado para cada item processado na lista. Que obj regexp deve ser re-utilizado para todos os itens.

  • não há nenhuma classe CSS utilizado para a formatação da parte concluída. É um estilo inline.
    Isto significa que se você tivesse vários autocompletes na mesma página, eles todos obter o mesmo tratamento. Um estilo css resolveria isso.

... mas ilustra a técnica principal, e ele funciona para suas necessidades básicas.

text alt

exemplo de trabalho atualização: http://output.jsbin.com/qixaxinuhe


Para preservar o caso das cordas jogo, em vez de usar o caso dos caracteres digitados, use esta linha:

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

Em outras palavras, a partir do código original acima, você só precisa substituir this.term com "$&".


Editar
As alterações acima todas autocomplete widget na página. Se você quiser alterar apenas uma, consulte esta pergunta:
Como corrigir * apenas um * instância de Autocomplete em uma página?

Outras dicas

isso também funciona:

       $.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);
        };

uma combinação de @ Jörn Zaefferer e @ respostas do Cheeso.

Super útil. Obrigado. +1.

Aqui está uma versão light que tipos de "String deve começar com o termo":

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 mudanças como _renderItem funciona.

O código abaixo assume essa mudança em consideração e também mostra como eu estava fazendo correspondência destaque usando o plugin jQuery Autocomplete de Jörn Zaefferer. Ela irá destacar todos os termos individuais no termo de pesquisa geral.

Desde que se mudou para usando Knockout e jqAuto Achei isso uma maneira muito mais fácil de pentear os resultados.

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

Aqui vai um exemplo completo funcional:

<!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>

Espero que isso ajude

para uma forma ainda mais fácil, tente o seguinte:

$('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)
});
  }

Aqui está uma nova versão da solução de Ted de Koning. Ele inclui:

  • Caso busca insensível
  • encontrando muitas ocorrências da procurou corda
$.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);
};

Aqui está uma versão que não requer quaisquer expressões regulares e corresponde a vários resultados no rótulo.

$.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);
};

Veja a demo combobox, que inclui o realce resultado: http://jqueryui.com / demos / autocomplete / # combobox

O regex em uso há também lida com resultados HTML.

Aqui é a minha versão:

  • Usa funções DOM em vez de RegEx para quebrar cordas / span injetar as tags
  • Somente o autocomplete especificado é afetado, nem todos
  • Funciona com UI versão 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);
};

Destaque combinado texto exemplo

Você pode usar folowing código:

lib:

$.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;
    }
});

e lógica:

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

cria costume widget que pode substituir _renderItem sem substituir _renderItem de protótipo plug-in originais.

no meu exemplo, também originais utilizadas tornar função para algum código simplificar

é importante se você quiser usar plug-in em diferentes lugares com visão diferente do autocomplete e não quero quebrar seu código.

Se você, em vez usar o 3o partido plugin, ele tem uma opção de destaque: http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions

(veja a página Opções)

Para suportar vários valores, simplesmente adicione o seguinte função:

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>");
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top