[{"id":1,"name":"JAVA"},{"id":2,"name":"cake PHP"},"id":3,"name":"Android"}]
例如,当我单击JAVA时,我想获得JAVA的ID,例如www.example.com/1
Jquery代码:
最佳答案
如果要将对象数组用作源,则需要提供以下逻辑:
>用于匹配用户输入的对象属性
>用于显示匹配项的文本的属性
>用户选择项目时使用的属性
更多信息:
> http://api.jqueryui.com/autocomplete/#option-source
> http://api.jqueryui.com/autocomplete/#method-_renderItem
> http://api.jqueryui.com/autocomplete/#event-select
var tags = [
{"id":1,{"id":3,"name":"Android"}
];
$( "#search" ).autocomplete({
source: function( request,response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ),"i" );
response( $.grep( tags,function( item ){
return matcher.test( item.name ); // match user request with item.name
}) );
},select: function( event,ui ) {
event.preventDefault();
$("#search").val( ui.item.name ); // display user selection in textBox
console.log('selected: ' + JSON.stringify(ui) );
console.log('execute window.location = "example.com/' + ui.item.id + '"'); // use id of the selected item to generate required URL
}
});
// provide rendering logic for each matched item
$w = $( "#search" ).data("ui-autocomplete");
$w._renderItem = function( ul,item ) {
//console.log(JSON.stringify(item) );
return $( "
编辑:根据您的评论使用typeahead.js.
var data =
[
{"id":1,"name":"Android"}
];
$(function(){
var substringMatcher = function(strs) {
return function(q,cb) {
var matches,substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q,'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`,add it to the `matches` array
$.each(strs,function(i,str) {
if (substrRegex.test(str.name)) {
matches.push(str);
}
});
cb(matches);
};
};
$('.typeahead').bind('typeahead:select',function(ev,suggestion) {
console.log('Selection: ' + JSON.stringify(suggestion) );
console.log('execute window.location = "example.com/' + suggestion.id + '"');
});
// passing in `null` for the `options` arguments will result in the default
// options being used
$('.typeahead').typeahead({
hint: true,minLength: 1
},{
source: substringMatcher(data),display: 'name'
});
});
更多信息:
> https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md
> https://twitter.github.io/typeahead.js/examples/#the-basics