[英]Select2 doesn't run on 'append'
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();
});
在這里您可以找到解決方案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>
我相信您的代碼中的問題是2 jQuery
。
檢查
JavaScript
和CSS
文件的順序。
我用過ES6
標准(模板文字)
希望這會幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.