$(document).ready(function () {
$("#search-title").autocomplete({
source: function ( request, response ) {
$.ajax({
url: "availabletags.json",
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response( $.map( data.stuff, function ( item ) {
return {
label: item.label,
value: item.value
};
}));
}
});
},
minLength: 2,
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
});
编辑: - 这是Json文件
{"stuff":[ {"label" : "Dragon", "value" : "eg.com"} ,
{"label" : "testing", "value" : "eg2.com"}]}
成功编辑的代码
<script>
$(document).ready(function () {
$("#search-title").autocomplete({
source: function ( request, response ) {
$.ajax({
url: "availabletags.json",
dataType: "json",
success: function (data) {
var sData = data.stuff.filter(function(v) {
var re = new RegExp( request.term, "i" );
return re.test( v.label );
});
response( $.map( sData, function ( item ) {
return {
label: item.label,
value: item.value
};
}));
}
});
},
minLength: 2,
focus: function (event, ui) {
this.value = ui.item.label;
event.preventDefault(); // Prevent the default focus behavior.
},
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
});
</script>
答案 0 :(得分:0)
以下是您要进行的更改:
dataType: "json",
success: function (data) {
var sData = data.stuff.filter(function(v) {
return v.value.indexOf( request.term ) > -1;
});
response( $.map( sData, function ( item ) {
此搜索将由value
完成。要按label
进行搜索,换句话说,要将用户的输入与JSON中的标签进行比较,请使用以下代码:
return v.label.indexOf( ........
<强>更新强>
要使搜索大小写不敏感,请使用以下命令:
var re = new RegExp( request.term, "i" );
return re.test( v.label );
而不是return v.value.indexOf( request.term ) > -1;