如何访问 bootstrapselect onChange 事件中的 optgroup 值

How to access the optgroup value in bootstrapselect onChange event

我正在使用表单中的 bootstrap-select 项,我想在 selected 值得到 [=16= 时得到 optgroup 值]et,所以我可以根据该组值评估要做什么:

$('select.selectpicker').on('change', function(e){

        var picker_id=e.target.id;
        var selected_value = $('.selectpicker option:selected').val();
        var optgroup = ??

        switch ( optgroup){
            case "group_name":

            break

        }
});    

感谢您的帮助。

你想获得'.selectpicker'class中的optgroups吗? 如果是这种情况,您可以使用

$('.selectpicker optgroup').length // will give you optgroups in the   selectpicker.
$('.selectpicker optgroup')[0].label // you can access attributes

您可以尝试以下方法:

$('select.selectpicker').on('change', function(e){
    var picker_id=e.target.id;
    var selected_option = $(this).find(":selected"); // get selected option for the changed select only
    var selected_value = selected_option.val();
    var optgroup = selected_option.parent().attr('label');

    console.log(optgroup);
    switch ( optgroup){
        case "group_name":

            break

    }
}); 

Example