【发布时间】:2018-06-30 09:24:44
【问题描述】:
我会尽量解释我的问题。我正在尝试使用select2 插件创建一种让用户编写一些字母的方法,并在每个字母上按下对 API 的调用,该 API 会给出该 API 给出的前 20 个结果。
所以我有我的 HTML 选择:
<select name="filtre_products[]" class="form-control products-select2" multiple>
</select>
然后是我的 JS(已注释):
$(".products-select2").select2({
width: '100%',
closeOnSelect: false,
placeholder: '',
minimumInputLength: 3,
query: function (query) {
var data = {results: []}, i, j, s;
if(query.term != null) {
var ajax_r = [];
$.ajax({
url: 'ajax_products_recherche.php?limite=10&real_json=1&recherche='+query.term,
success: function(data_a){
//Getting the data
data_a = JSON.parse(data_a);
//Looping through the each data and putting them inside a table
data_a.forEach( (e) => {
ajax_r.push(e);
});
//Filtering the data to get from it the id and the text to be used
ajax_r.forEach( (e) => {
var tmp = e.split('-');
var id = tmp[0];
var name = tmp[2];
data.results.push({value: id, text: name});
});
query.callback(data);
}
});
}
},
//Sending the results to the function to modify the options as I please
templateResult: formatResult
});
这是我使用的formatResult 函数:
function formatResult(d) {
if(d.loading) {
return d.text;
}
// Creating an option of each id and text
$d = $('<option/>').attr({ 'value': d.value }).text(d.text);
return $d;
}
我的问题是 select2 应该在初始化时动态创建选项,因此实际上从选项中创建 <li> 并动态添加它们的 ID 等。但是在我创建它的方式中,它将选项放在<li> 标记内,这不是我想要的,我希望它像他在没有查询调用的情况下那样将其视为动态选项。
为你们提供一些文档资源,它显示了我正在尝试做的一部分,但该示例显示了如何显示我们编写的结果,我希望它在每次点击时从 api 中显示,以及课程添加了多项选择: http://select2.github.io/select2/#data
【问题讨论】:
标签: javascript jquery jquery-select2