繁体   English   中英

为什么当我 append html 时 select2 不起作用

[英]why select2 doesn't work when i append html

我在使用 select2 时遇到问题。 我想更改类别过滤器,但是当 append select2 中的数据不起作用时。 解决这个问题的解决方案是什么?

在此处输入图像描述

$(document).on('change', '#filterbySelect1', function (event) {
    event.preventDefault();
    var selectVal = $('#filterbySelect1').val();
    if (selectVal == 'categoryBook') {
        $('.filter').append('<div class="form-group mb-5">'
            + '<label for="selectbyCategory">Filter Berdasarkan Katagori</label>'
            + '<select class="select2bs4" multiple="multiple" data-placeholder="Pilih Kategori" style="width: 100%;">'
            + '<option>Alabama</option>'
            + '<option>Alaska</option>'
            + '</select>'
            + '<small id="emailHelp" class="form-text text-muted">Maksimal memilih 3 kategori</small>'
            + '</div>');
    }
});

//Initialize Select2 Elements
$('.select2').select2();

//Initialize Select2 Elements
$('.select2bs4').select2({
    theme: 'bootstrap4',
    dropdownParent: $('.filter')
});

当您重新创建新的 select 时,请在您的 select2 创建的事件中初始化:

$(document).on('change', '#filterbySelect1', function (event) {
    event.preventDefault();
    var selectVal = $('#filterbySelect1').val();
    if (selectVal == 'categoryBook') {
        $('.filter').append('<div class="form-group mb-5">'
            + '<label for="selectbyCategory">Filter Berdasarkan Katagori</label>'
            + '<select class="select2bs4" multiple="multiple" data-placeholder="Pilih Kategori" style="width: 100%;">'
            + '<option>Alabama</option>'
            + '<option>Alaska</option>'
            + '</select>'
            + '<small id="emailHelp" class="form-text text-muted">Maksimal memilih 3 kategori</small>'
            + '</div>');
           
           //Initialize Select2 Elements
           $('.select2bs4').select2({
              theme: 'bootstrap4',
              dropdownParent: $('.filter')
           });

    }
});

//Initialize Select2 Elements <--- initialize another select2?
$('.select2').select2();

//Initialize Select2 Elements
//$('.select2bs4').select2({
//    theme: 'bootstrap4',
//    dropdownParent: $('.filter')
//});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM