使匹配的字母自动完成突出的JavaScript / jQuery的 [英] Make matched letters highlighted in autocomplete in javascript/jquery
问题描述
我有一组机场的名字与他们的codeS中自动完成一起显示。
I have a set of airport names along with their codes to be displayed in autocomplete.
例如。 Amsterdem(AMS)
E.g. Amsterdem (AMS)
我想匹配在搜索框中输入的值,我想按如下方式显示粗体匹配的机场名称以及机场code。
I want to match the value entered in the search box,I want to display the matched airport name as well as airportcode bold as follows.
如果我在搜索框中输入的 AMS ,我想强调'了Ams terdem( AMS )在我的自动完成。
if I enter ams in search box,i want to highlight 'Ams'terdem ('AMS') in my autocomplete.
我已经写了code如下:
I have written a code as below:
function () {
var oldFn = $.ui.autocomplete.prototype._renderItem;
$.ui.autocomplete.prototype._renderItem = function( ul, item) {
var re = new RegExp("^" + this.term, "i") ;
var t = item.label.replace(re,"<span style='font-weight:bold;'>" + this.term + "</span>");
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + t + "</a>" )
.appendTo( ul );
};
};
它的结果为了Ams terdem(AMS),而不是了Ams terdem( AMS )。
it results as 'Ams'terdem (AMS) instead of 'Ams'terdem (AMS).
请注意:Amsterdem(AMS)是一个长期
Note:Amsterdem (AMS) is a single term
请咨询。
推荐答案
您必须修改
var re = new RegExp("^" + this.term, "i") ;
本code
var re = new RegExp(this.term, "ig") ;
这将替换所有实例的字符串
this will replace all instance in your string
^表示字符串的开始,G适用于所有情况。
"^" denotes start of string, and "g" in regular expression works on all instance
这里正在例如
这一个取代你的code
replace your code with this one
function () {
var oldFn = $.ui.autocomplete.prototype._renderItem;
$.ui.autocomplete.prototype._renderItem = function( ul, item) {
var re = new RegExp(this.term, "ig") ;
var t = item.label.replace(re,"<span style='font-weight:bold;'>" + this.term + "</span>");
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + t + "</a>" )
.appendTo( ul );
};
};
这篇关于使匹配的字母自动完成突出的JavaScript / jQuery的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!