github地址:https://github/ttskch/select2-bootstrap4-theme

引入Selelct2的CSS文件,按路径查找

其次引入Selelct2的JavaScript文件

地址:https://cdn.jsdelivr/npm/select2@4.1.0-rc.0/dist/js/select2.min.js

使用,这里我就使用几条数据

<select class="single-select">
	<optionvalue="United States">哈哈哈</option>
	<option value="United Kingdom">United Kingdom</option>
	<option value="Afghanistan">Afghanistan</option>
	<option value="Aland Islands">Aland Islands</option>
	<option value="United Kingdom">United Kingdom</option>
	<option value="Afghanistan">Afghanistan</option>
	<option value="Aland Islands">Aland Islands</option>
</select>

在JavaScript中引入

$('.single-select').select2({
	theme: 'bootstrap4',
	// 这个是需要在模态框中使用必须加的语句,搜索框渲染时绑定到这个id的div
  	dropdownParent:$('#course-lesson-form'),
 	width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
  	placeholder: $(this).data('placeholder'),
 	allowClear: Boolean($(this).data('allow-clear')),
});

dropdownParent:$(’#course-lesson-form’):这个是需要在模态框中使用必须加的语句,因为要让模态框显示出来再去执行下拉框的JavaScript的代码,在使用模态框与Select2结合最坑的地方就是这个了。

效果图

更多推荐

在BootStrap的modal(模态框)中使用Select2(下拉框带搜索框)