Javascript 选择2打开并刷新时添加选项值

Javascript 选择2打开并刷新时添加选项值,javascript,jquery-select2,Javascript,Jquery Select2,我有一个select2元素,当用户单击它时,我需要将元素添加到该元素中。为了实现这一点,我聆听select2开场白并添加元素 $('#select2_elem').on('select2-opening', function (evt) { $('#select2-elem').append('<option value="1">val1...</option>'); }); $('select2_elem')。打开('select2-opening',函数(e

我有一个select2元素,当用户单击它时,我需要将元素添加到该元素中。为了实现这一点,我聆听select2开场白并添加元素

$('#select2_elem').on('select2-opening', function (evt) {
    $('#select2-elem').append('<option value="1">val1...</option>');
});
$('select2_elem')。打开('select2-opening',函数(evt){
$('select2 elem')。追加('val1…');
});

这很好(即在DOM中附加选项),只是我没有立即看到附加的选项。有什么方法可以刷新吗?

使用
$(this)
获取对当前选择元素的引用

$('select2_elem')。打开('select2-opening',函数(evt){
$(this.append('val1…');
});
$('#select2_elem').on('select2-opening', function (evt) {
    $(this).append('<option value="1">val1...</option>');
});