我试图从json中提取一些数据并使用jquery自动完成显示它们。
json数组包含ID,Title,Date。在显示屏上,我想显示标题和日期,点击后我想解析该标题的特定ID。
所以目前我有:
$("input").autocomplete({
source: function (d, e) {
$.ajax({
type: 'GET',
url: url + mode + encodeURIComponent(d.term) + key,
dataType: "jsonp",
success: function (b) {
var c = [];
$.each(b.results, function (i, a, k) {
c.push(a.title + " " + a.date) // Displays Title and Date
});
e(c)
}
})
},
select: function (a, b) {
console.log(b);
// Appends an array with 2 keys: Value and Label.
// Both display the title and date as shown above.
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>"+ item.label + "</a>" )
// Here I want to append a.id as class of this
// but the only values are value and label.
.appendTo( ul );
};
那么如何追加<li class="' + a.id + '">" + a.title + " " + a.date + "</li>"
答案 0 :(得分:4)
你正在使用AJAX成功函数中的$.each
循环剥离额外的属性(作为旁注,我很确定$.each
的回调不会带第三个参数) 。只需将label
属性附加到每个结果项,它应该可以正常工作:
source: function (d, e) {
$.ajax({
type: 'GET',
url: url + mode + encodeURIComponent(d.term) + key,
dataType: "jsonp",
success: function (b) {
var c = [];
$.each(b.results, function (i, a) {
a.label = a.title + " " + a.date;
c.push(a);
});
e(c);
}
})
},
小部件可以与额外属性一起使用,只需必须至少拥有label
或value
属性。
现在,在_renderItem
功能中,您可以访问每个项目的title
和date
属性:
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>"+ item.label + "</a>" )
.addClass(a.id) // <---
.appendTo( ul );
};
答案 1 :(得分:3)
试试这个。将ID放在ajax调用的值中。
$( "input" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: url + mode + encodeURIComponent(d.term) + key,,
dataType: "jsonp",
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.title ", " + item.date,
value: item.id
}
}));
}
});
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<li "+ "class="+"item.value + ">"item.label + "</li>" )
.appendTo( ul );
};
答案 2 :(得分:0)
在$ .ajax成功时,您应该传递包含标签和值的对象而不是标签字符串,然后您可以将a.id分配给item.value。像这样:
$("input").autocomplete({
source: function (d, e) {
$.ajax({
type: 'GET',
url: url + mode + encodeURIComponent(d.term) + key,
dataType: "jsonp",
success: function (b) {
var c = [];
$.each(b.results, function (i, a, k) {
c.push({'value':a.id, 'label':a.title + " " + a.date}) // Displays Title and Date
});
e(c)
}
})
},
select: function (a, b) {
console.log(b);
// Appends an array with 2 keys: Value and Label.
// Both display the title and date as shown above.
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li class=\""+item.value+"\"></li>" )
.data( "item.autocomplete", item )
.append( "<a>"+ item.label + "</a>" )
.appendTo( ul );
};
您也可以将原始对象作为标签(c.push({'value':a.id, 'label':a})
)传递,并保留_renderItem
的格式(其中item.label
与a
相同)