Cly*_*deM 4 jquery jsonp jquery-ui autocomplete jquery-ui-autocomplete
我正在尝试从 json 中提取一些数据并使用 jquery 自动完成功能显示它们。
json 数组包含 ID、标题、日期。在显示屏上,我想显示标题和日期,单击时我想解析该标题的特定 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 );
};
Run Code Online (Sandbox Code Playgroud)
那么我该如何附加 <li class="' + a.id + '">" + a.title + " " + a.date + "</li>"
您正在使用$.eachAJAX 成功函数内的循环去除额外的属性(作为旁注,我很确定$.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);
}
})
},
Run Code Online (Sandbox Code Playgroud)
该小部件可以与额外的属性一起正常工作,您只需要至少有一个labelorvalue属性。
现在在您的_renderItem函数中,您可以访问每个项目的titleanddate属性:
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>"+ item.label + "</a>" )
.addClass(a.id) // <---
.appendTo( ul );
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18915 次 |
| 最近记录: |