我正在尝试在jquery中使用国家代码进行自动补全。我使用这个code作为例子。在我的站点中,它工作得非常好,但是值以列表的形式出现在输入的前面,而不像站点中的示例。我不能在jsfiddle上运行它,但这是my code。谢谢你!
var countries = {
"Argentina (AR)":"AR",
"United States (US)":"US",
"Comoros": "KM",
"Congo (Brazzaville)": "CG",
"Congo, Democratic Republic of the": "CD",
"Cook Islands": "CK",
"Costa Rica": "CR",
"Côte d'Ivoire": "CI",
"Croatia": "HR",
"Cuba": "CU",
"Cyprus": "CY",
"Czech Republic": "CZ",
"Denmark": "DK",
"Djibouti": "DJ",
"Dominica": "DM",
"Dominican Republic": "DO",
};
$( "#countryCodes" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB && $( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
Object.keys(countries), extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( countries[ui.item.value] );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( "," );
return false;
}
});发布于 2016-02-05 23:48:21
小提琴中缺少exactLast函数。我添加了现在和这里,现在它可以在小提琴中工作
function extractLast( term ) {
return split( term ).pop();
}https://jsfiddle.net/px2dmd1o/1/
检查并让我知道你的问题是什么
发布于 2016-02-05 23:20:23
一种解决方案是为自动补全提供源数组。jQuery的自动完成功能要求源数组包含具有label和value属性的对象。您可以在定义countries对象后构建此数组,例如:
var mySource = Object.keys(countries).map(function(country) {
return {
label: country,
value: countries[country]
};
});然后,...and将其提供给autocomplete:
$('#countryCodes').autocomplete({
source: mySource
});为了让您的小提琴运行,我必须注释掉您传递给自动完成小部件的其余内容,因为它有一些未定义的函数。
https://stackoverflow.com/questions/35227276
复制相似问题