问题
My select2 is not working. It just shows up with multiple selectbox
<form action="">
<select class="js-example-basic-multiple" multiple="multiple">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
<option value="CA">California</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
<option value="AZ">Arizona</option>
<option value="CO">Colorado</option>
<option value="ID">Idaho</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NM">New Mexico</option>
<option value="ND">North Dakota</option>
<option value="UT">Utah</option>
<option value="WY">Wyoming</option>
</select>
</form>
<script type="text/javascript">
$(".js-example-basic-multiple").select2();
</script>
Error in console: Uncaught TypeError: $(...).select2 is not a function at HTMLDocument.
JS FIDDLE:
https://jsfiddle.net/y6ogss94/
回答1:
This runs fine if you have imported correctly - jQuery library, select2 js and select2 css.
Here I have imported jquery 2.0.0 and select2 css and js from their cdn and it works fine:
$(".js-example-basic-multiple").select2();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<form action="">
<select class="js-example-basic-multiple" multiple="multiple">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
<option value="CA">California</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
<option value="AZ">Arizona</option>
<option value="CO">Colorado</option>
<option value="ID">Idaho</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NM">New Mexico</option>
<option value="ND">North Dakota</option>
<option value="UT">Utah</option>
<option value="WY">Wyoming</option>
</select>
</form>
Note: You need to execute your select2 initialisation code only after you have included both the js libraries and DOM has loaded, which is a general practice for most jQuery plugins, not only this. So, while using this code you should write this script after including jquery and select2 scripts:
<script>
$(document).ready(function(){
$(".js-example-basic-multiple").select2();
});//document ready
</script>
来源:https://stackoverflow.com/questions/41277344/select2-is-not-working