【发布时间】:2014-10-04 15:15:19
【问题描述】:
我正在使用 jQuery 的自动完成功能向用户显示文本输入字段的建议,但我很难将建议列表中的匹配文本设置为粗体。例如,如果用户开始输入“balt”,则显示的每个自动完成建议中的文本“balt”都应该像这样加粗:
“巴尔特美国伊莫尔 - 巴尔特伊莫尔国际机场 (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);
}
});
【问题讨论】:
-
你能做个小提琴吗?
-
var ph 是一个字符串,而不是一个 jquery 对象,所以高亮插件不起作用。
-
当您可以在显示时呈现 jquery 对象(选择器)时,为什么要将 html 放入 json 对象中
-
您需要将 jQuery UI 添加到您的外部资源中,否则您的小提琴将无法正常工作
标签: jquery autocomplete jquery-autocomplete