JQuery UI 自动完成:如何在插入输入字段之前从标签中剥离标签?
我正在使用 JQuery UI 自动完成,我有一组通过 ajax 返回的项目,其中的术语由搜索引擎突出显示(因此标签已经包含 html)。问题是,每次我选择一个项目时,带有 html 标签的值都会插入到文本框中,这当然不好。我想知道是否可以在插入文本框之前从标签上删除所有标签
var cache = {}, lastXhr;
$('#location_name').autocomplete({
source: function( request, response ) {
var q = request.term;
if ( q in cache ) {
response( cache[ q ] );
return;
}
lastXhr = $.getJSON( "location_search/", {q: q}, function( data, status, xhr ) {
$.each(data, function(i, v){
data[i].label = v.name + (v.address !== null ? ', ' + v.address : '');
});
cache[ q ] = data;
if ( xhr === lastXhr ) {
response( cache [q] );
}
});
},
select: function( event, ui ) {
$('#location_id').val(ui.item.id);
$('#selected_location').html(ui.item.label);
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>"+ item.label + "</a>" ) // + + "<br>" + item.desc + "</a>"
.appendTo( ul );
};
I'm using JQuery UI Autocomplete, I have the set of items returned via ajax with the terms highlighted by the search engine (so the label already contains the html). The problem is that every time I choose an item the value with html tags is inserted into the text box which is of course not nice. I wonder if there is anyway I can strip all tags from the label before inserting into the text box
var cache = {}, lastXhr;
$('#location_name').autocomplete({
source: function( request, response ) {
var q = request.term;
if ( q in cache ) {
response( cache[ q ] );
return;
}
lastXhr = $.getJSON( "location_search/", {q: q}, function( data, status, xhr ) {
$.each(data, function(i, v){
data[i].label = v.name + (v.address !== null ? ', ' + v.address : '');
});
cache[ q ] = data;
if ( xhr === lastXhr ) {
response( cache [q] );
}
});
},
select: function( event, ui ) {
$('#location_id').val(ui.item.id);
$('#selected_location').html(ui.item.label);
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>"+ item.label + "</a>" ) // + + "<br>" + item.desc + "</a>"
.appendTo( ul );
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
添加此函数:
并添加到您的代码中:
Add this function:
And add to your code:
为了使这项工作正常进行,您还应该
在选择时传递 item.value ,它首先查找 item.value,然后查找 item.label
你可以留下你的选择的方式:像那样
In order to make this work you should also pass item.value
On select it looks for item.value first and then for item.label
That way you can leave your select: like that