【发布时间】:2015-09-11 09:12:47
【问题描述】:
几个小时后,我终于让 json 文件加载并正确显示,包括使用 Select2 4.0 的标志图标,看看代码看起来多么简单,这很荒谬。
但是现在,由于某种原因,搜索功能无法正常工作。我无法搜索任何选项。
希望它既快速又简单,而且我可以打自己的头,因为没有早点发现它。
HTML:
<select id="country_select" class="form-control"></select>
JS:
<script>
function formatCountry (country) {
if (!country.id) { return country.text; }
var $country = $(
'<span><img src="/assets/img/flags/' + country.code.toLowerCase() + '.png" class="flag" /> ' + country.text + '</span>'
);
return $country;
};
$('#country_select').select2({
templateResult: formatCountry,
templateSelection: formatCountry,
ajax: {
url: '/assets/json/countries.json',
dataType: 'json',
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, page) {
return {
results: $.map(data, function(country) {
return { id: country.id, code: country.code, text: country.name };
})
};
}
}
});
</script>
JSON:
{
"id":53,
"code":"CW",
"name":"Curaçao",
"iso_alpha_3":"CUW",
"iso_numeric":531
},
{
"id":54,
"code":"CX",
"name":"Christmasøya",
"iso_alpha_3":"CXR",
"iso_numeric":162
},
{
"id":55,
"code":"CY",
"name":"Kypros",
"iso_alpha_3":"CYP",
"iso_numeric":196
},
【问题讨论】:
-
json和html是什么样子的
-
我用 JSON 更新了,HTML 已经存在了。我已经在没有任何 CSS 并加载相同数据的小提琴上进行了尝试,但在那里搜索也不起作用。
标签: javascript jquery json jquery-select2