我有一个需要使用select2组件的网页。还需要在加载时显示选定的值。在我的JS文件中,我有两个构造
JS - 构造1用于选择/删除选项
$("#inp_select_linkproject").select2({
minimumInputLength: 2,
maximumSelectionLength: 1,
ajax: {
type : 'POST',
url: '../../ase.php',
dataType: 'json',
delay: 250,
data: function (term, page) {
return {
wildcardsearch: term, // search term
data_limit: 10,
data_offset: 0,
page_mode:"SELECT",
agent_id:$("#ipn_hdn_userid").val()
};
},
processResults: function (data, page) {
return { results: data.dataset};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
});
JS - Construct 2 for catering onload
$.fn.getCurrentSelect2data = function(){
$("#inp_select_linkproject").val(null).trigger("change");
var $element = $('inp_select_linkproject').select2(); // the select element you are working with
var postFormData = {
'eucprid' : $("#ipn_hdn_eucprid").val()
};
var $request = $.ajax({
type : 'POST',
url: '../../ase_x.php',
data : postFormData,
dataType: 'json'
});
$request.then(function (data) {
// This assumes that the data comes back as an array of data objects
// The idea is that you are using the same callback as the old `initSelection`
console.log("rowselect,data0-"+data[0].text);
for (i=0; i<data.length; i++) {
$('#inp_select_linkproject').append($("<option/>", {
value: data[i].id,
text: data[i].text,
selected: true
}));
}
$('#inp_select_linkproject').trigger('change');
});
}
现在的问题是重复选择正在发生,选择更多选项时重复次数也会增加。你能帮帮我吗?
答案 0 :(得分:2)
您遇到的问题并非特定于Select2,如果您从代码中删除对Select2的调用,您会发现它也符合标准<select>
。问题是您在注册新选择之前没有清除旧的选择,因此它们只是附加到结尾(并导致重复)。
您可以通过调用
来解决此问题$select.empty();
在您开始向$select
添加新选项之前。在您的情况下,这意味着将您的回调更改为
// clear out existing selections
$('#inp_select_linkproject').empty();
// add the selected options
for (i=0; i<data.length; i++) {
$('#inp_select_linkproject').append($("<option/>", {
value: data[i].id,
text: data[i].text,
selected: true
}));
}
// tell select2 to update the visible selections
$('#inp_select_linkproject').trigger('change');