2017-09-11 11 views
2

Select2関数が新しいselectタグを追加するときに開かず、コンソールにこのエラーがあります(Uncaught TypeError:$(...)。select2は関数ではありません)。Select2が 'append'で実行されない

<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(); 
    }); 
+0

select2()を使用する場合は、関数を実行するには、単にselect2()を使用します。 $( '。select2')の代わりに。select2(); – Keith

+0

動作しません。 – user3721008

+0

は私のために働くhttps://jsfiddle.net/cx5m40wu/1/ – Keith

答えて

0

ここでは、私はあなたのコードで問題が2 jQueryであると信じソリューション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>

で行きます。

Check the order of JavaScript & CSS files.

私はES6標準(テンプレートリテラル)これはあなたを助ける

希望を使用しました。

関連する問題