繁体   English   中英

jQuery select2 在模态中出现问题

[英]jQuery select2 appearence issue in modal

我在模态中使用 jQuery select2 ......但它的外观不正确......你可以在下图中看到它......如何解决这个问题? 问题仅发生在模态内部。 图片

<div class="col">
   <label class="control-label">Department*</label>
      <select class="form-control select2" name="department_id">
         <option value="" selected>Select Department</option>
             @foreach ($departments as $value)
                <option value="{{ $value->id }}">{{ $value->name }}</option>
             @endforeach
     </select>
</div>

Jquery 用于模态,

function viewCreate() {
        if (typeof device !== 'undefined')
            device.abort();
        device = $.ajax({
            type: 'GET',
            url: "devices/create/",
            dataType: 'JSON',
            async: true,
            beforeSend: function () {
                if (typeof device !== 'undefined')
                    device.abort();
            },
            success: function (response) {                   
                $('#showData').html(response.data);
                $('.showModal').modal('show');
            }
        });
    }

问题是因为 Select2 库在模态内容在 DOM 中可见之前被实例化。 因此,它会导致渲染问题,因为无法准确计算元素使用的空间。

要解决此问题,您可以挂钩到shown.bs.modal事件并在模态可见后初始化 Select2 元素:

// outside the AJAX call:
$('.showModal').on('shown.bs.modal', e => {
  $(e.target).find('.select2').select2({ /* your config options here... */ });
});

您需要在 js 文件中调用 select2,如下所示:

$(document).ready(function() {
    $('#department_id').select2();
});

我不确定这是你的问题,但我希望它对你有用。

暂无
暂无

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

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