[英]Select2 doesn't run on 'append'
Select2 function doesn't open on appending new select tag, and console has this error (Uncaught TypeError: $(...).select2 is not a function). Select2函数在添加新的select标签时无法打开,并且控制台出现此错误(Uncaught TypeError:$(...)。select2不是函数)。
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js'></script>
$(document).on('click', '#addNewItem', function() {
var a = $(".gh").val();
a++;
$('.asd').append('<select class="form-control select2" name="ProposalItemName[]">' +
'<optgroup label="Items">' +
'<option>test</option>' +
'<option>test</option>' +
'</optgroup>' +
'</select>');
$('.select2').select2();
});
Here you go with a solution https://jsfiddle.net/cx5m40wu/2/ 在这里您可以找到解决方案https://jsfiddle.net/cx5m40wu/2/
$(document).on('click', '#addNewItem', function() { var a = $(".gh").val(); a++; $('.asd').append(`<select class="form-control select2" name="ProposalItemName[]"> <optgroup label="Items"> <option>test</option> <option>test</option> </optgroup> </select>`); $('.select2').select2(); });
.alignRight{ float: right; padding-left: 15px; }
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script> <div class="asd"> test </div> <button id="addNewItem" type="button"> Click </button>
I believe the issue in your code is 2 jQuery
. 我相信您的代码中的问题是2 jQuery
。
Check the order of
JavaScript
&CSS
files. 检查JavaScript
和CSS
文件的顺序。
I've used ES6
standard (template literals) 我用过ES6
标准(模板文字)
Hope this will help you. 希望这会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.