[英]How to format JQueryUI autocomplete response?
I am trying to make an autocomplete widget that will display the name and a short description of the matched item. 我正在尝试创建一个自动完成小部件,它将显示匹配项的名称和简短描述。
For example, if I type "America" it will show "North America - The northern subcontinent of the Americas." 例如,如果我输入“美”则显示“ 北美 -美洲的北部次大陆。” and "South America - The southern subcontinent of the Americas."
和“ 南美洲 - 美洲南部次大陆”。
I have successfully made it so my database will return the appropriate JSON response with id,value (name of the item, eg. North America, and desc (short description eg. 'The northern subcontinent...'), I just need help to format the returned results as 我已成功完成,所以我的数据库将返回相应的JSON响应,其中包含id,value(项目名称,例如北美和desc(简短说明,例如'北部次大陆......'),我只需要帮助将返回的结果格式化为
<li><strong>value<strong><br><p>desc</p></li>
instead of just 而不仅仅是
<li>value</li>
Thanks a lot in advance. 非常感谢提前。
PS I have been trying to look for an answer on Stack Overflow, but the answers I've found involve formatResult and other methods that are no longer supported. PS我一直试图在Stack Overflow上寻找答案,但我发现的答案涉及formatResult和其他不再支持的方法。
http://jqueryui.com/demos/autocomplete/#custom-data - 是jquery ui网站上你想要实现的自定义数据示例吗?
this may be of help,look at the .data(): 这可能有所帮助,看看.data():
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.label );
$( "#project-id" ).val( ui.item.value );
$( "#project-description" ).html( ui.item.desc );
$( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
You should be able to use the following RegEx to achieve the result you are looking for. 您应该能够使用以下RegEx来实现您正在寻找的结果。
item.label.replace(new RegExp('(' + term + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>';
});
The full example is below. 完整的例子如下。
$("#project").autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.label );
$( "#project-id" ).val( ui.item.value );
$( "#project-description" ).html( ui.item.desc );
$( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
var term = this.term,
formattedLabel = item.label.replace(new RegExp('(' + term + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>';
});
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + formattedLabel + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.