2014-10-04 2 views
0

Я использую автозаполнение jQuery для отображения предложений пользователю для текстового поля ввода, и мне сложно сделать соответствующий текст в списке предложений полужирным. Например, если пользователь начинает вводить в «Balt», текст «Balt» в каждом из предложений автозаполнения отображенных должны быть подчеркнуты, как это:jQuery Autocomplete - как сделать соответствующий текст полужирным

"Balt imore, США - Balt imore Intl. (BWI) "

(похоже на то, что Kayak.com делает в своей поисковой форме).

JS:

var airportList = [ 
{"IATA":"BWI","city":"Baltimore","airp":"Baltimore Intl.","country":"USA"}, 
{"IATA":"SEA","city":"Seattle","airp":"Seattle Tacoma Intl.","country":"USA"}, 
{"IATA":"LAX","city":"Los Angeles","airp":"Los Angeles Intl.","country":"USA"}, 
{"IATA":"JFK","city":"New York","airp":"John F. Kennedy Intl.","country":"USA"}]; 

$("#input1").autocomplete({ 
    minLength: 3, 
    source: function(request, response){ 

    var searchTerm = request.term.toLowerCase(); 
    var ret = []; 
    var ph; 
    $.each(airportList, function(i, airport){ 
     if (airport.city.toLowerCase().indexOf(searchTerm) === 0 || airport.IATA.toLowerCase().indexOf(searchTerm) !== -1 || airport.country.toLowerCase().indexOf(searchTerm) === 0 || airport.airp.toLowerCase().indexOf(searchTerm) === 0) { 
     ph = airport.city + ', ' + airport.country + ' - ' + airport.airp + ' (' + airport.IATA + ')'; 

     // ph is each suggestion that will appear in the suggestions list, i need to 
     // make the substring in ph that matches the searchTerm appear bold; I've tried 
     // replacing the substring with the same substring with <strong> tags around it 
     // and the .bold() function, neither worked. 

     ret.push(ph); 
     } 

     }); 

     response(ret); 
    } 
}); 

скрипка: http://jsfiddle.net/ray9209/v9o71L11/2/

+0

Вы можете сделать скрипку? –

+0

Вот, посмотрите на это: http://bartaz.github.io/sandbox.js/jquery.highlight.html –

+0

var ph - это строка, а не объект jquery, поэтому основной плагин не будет работать. – ray9209

ответ

1

Для достижения этой цели следует использовать функцию _renderItem, которая в основном Отрисовывает элементов в списке результатов. В этой функции вы замените искомую строку новой строкой, окруженной тегом.

var airportList = [ 
{"IATA":"BWI","city":"Baltimore","airp":"Baltimore Intl.","country":"USA"}, 
{"IATA":"SEA","city":"Seattle","airp":"Seattle Tacoma Intl.","country":"USA"}, 
{"IATA":"LAX","city":"Los Angeles","airp":"Los Angeles Intl.","country":"USA"}, 
{"IATA":"JFK","city":"New York","airp":"John F. Kennedy Intl.","country":"USA"}]; 

$("#input1").autocomplete({ 
minLength: 3, 
source: function(request, response){ 

var searchTerm = request.term.toLowerCase(); 
var ret = []; 
var ph; 
$.each(airportList, function(i, airport){ 
    if (airport.city.toLowerCase().indexOf(searchTerm) === 0 || airport.IATA.toLowerCase().indexOf(searchTerm) !== -1 || airport.country.toLowerCase().indexOf(searchTerm) === 0 || airport.airp.toLowerCase().indexOf(searchTerm) === 0) { 
    ph = airport.city + ', ' + airport.country + ' - ' + airport.airp + ' (' + airport.IATA + ')'; 

    // ph is each suggestion that will appear in the suggestions list, i need to 
    // make the substring in ph that matches the searchTerm appear bold; I've tried 
    // replacing the substring with the same substring with <strong> tags around it 
    // and the .bold() function, neither worked. 

    ret.push(ph); 
    } 

    }); 

    response(ret); 
} 
}).data("ui-autocomplete")._renderItem = function(ul, item) { 
    return $("<li>") 
    .attr("data-value", item.value) 
    .append($("<a>").html(item.label.replace(new RegExp(this.term, 'gi'),"<b>$&</b>"))) 
    .appendTo(ul); 
}; 
0

Проблемы вы испытываете это вы инициализацию вашего автозаполнения со статическим источником и ожидая, чтобы показать различные данные каждый раз, когда вы поиск.

Вместо этого поместите ваш процесс выделения для в response() случае захватить возвращаемые данные после каждого поиска, прежде чем он делает, например, так:

,response: function(event, ui) { 
    //render through the ui object here to update the highlighting on the results. 
    if(ui.length>0){ 
    ui[0].label = "highlighted text"; 
    } 
}