【问题标题】:Programmatically Adding an Option with Extra Data以编程方式添加带有额外数据的选项
【发布时间】:2021-10-28 18:39:14
【问题描述】:

我有一个带有 ajax 数据源的 select2 多选元素。我需要在加载时使用预选选项自动填充我的 select2。我按照说明in the docs 填充选项,这可以正常工作。但是,它似乎没有添加我传入的额外数据 - 它只有 ID 和文本。

这是我的代码的简化版本:

// create the option and append to Select2
let option = new Option('value', 'id', true, true);
$('#mySelect2').append(option).trigger('change');

// manually trigger the `select2:select` event; pass all data
let data = {
    id: 'id',
    text: 'value',
    anotherId: 'anotherID',
    moreData: 'moreData'
};
$('#mySelect2').trigger({
    type: 'select2:select',
    params: {
        data: data
    }
});

然而,当我尝试通过$('#mySelect2').select2('data') 访问选定的元素时,额外的属性(anotherId、moreData)不存在。我怎样才能传递额外的数据,以便它模仿用户实际从下拉列表中选择一个选项时发生的情况? (然后调用select2('data')时会显示额外的数据属性。)

【问题讨论】:

    标签: jquery ajax jquery-select2


    【解决方案1】:

    我找不到直接的方法,所以我添加了代码来手动破解它(强行将它添加到 select2 数据中)。

    // create the option and append to Select2
    let option = new Option('value', 'id', true, true);
    $('#mySelect2').append(option).trigger('change');
    
    let data = {
        id: 'id',
        anotherId: 'anotherID',
        moreData: 'moreData'
    };
    
    // modify the added option manually - add extra data attributes (in addition to id and text)
    let $current_option_data = $(this).select2('data').find(function (currentOption) {
        return currentOption.id == data['id']
    });
    if ($current_option_data) {
        $current_option_data['anotherId'] = e.params.data['anotherId'];
        $current_option_data['moreData'] = e.params.data['moreData'];
    }
    
    // manually trigger the `select2:select` event
    $('#mySelect2').trigger({
        type: 'select2:select'
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      相关资源
      最近更新 更多