【发布时间】:2015-12-24 02:09:25
【问题描述】:
我有一个 select2 选择菜单正在工作(来自远程地理字节的状态),但我无法选择具有相同索引 ID 的选项。例如,如果我搜索“新”,我会得到一些选项,我可以选择第一个选项 New Albany, IN。然后,如果我输入“far”,第一个选项是 Far Hills, NJ。当我选择它时,它显示 Albany, IN,它的索引为 1。
我尝试了加载远程数据的示例https://select2.github.io/examples.html#data-ajax。它的行为方式不同,所以我想知道我是否错误地解析了我的结果。每次搜索时,它都会返回一个索引以 1 开头的新对象。
$('#input_3_4').select2({
ajax: {
url: "http://gd.geobytes.com/AutoCompleteCity?callback=?&template=%3Cgeobytes%20city%3E,%20%3Cgeobytes%20code%3E&filter=US",
dataType: 'json',
quietMillis: 1500,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
for(var i = 0; i < data.length; i++){
data[i] = {id:i+1, text:data[i]};
}
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
console.log(data);
return {
results: data,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true,
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 3,
//templateResult: formatRepo, // omitted for brevity, see the source of this page
//templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
【问题讨论】:
-
我怀疑这是因为您每次都从 1 开始重用相同的 ID。文档中的示例使用了 github API 返回的 ID,它们是唯一的。
-
有什么办法可以避免这种情况吗?从 geobytes 传回来的数据是这样的:
?(["New York Mills, MN, United States","New York Mills, NY, United States","New York, NY, United States"]); -
使用全局变量来跟踪您分配的最后一个 ID,并从那里每次递增。
-
谢谢!我会试试的。
-
成功了。我在 select2 函数之外声明了一个变量
var dataIndex = 1;,然后在 processresults 的 for 循环中增加了 dataIndex。按照您的指示跟踪我分配的最后一个 ID 是否更好?这似乎工作得很好,也很容易,但我不擅长 javascript。