未捕获的TypeError:$(…)。select2不是函数

我下载了select2包,并将两个文件select2.min.css和select2.min.js包含到我的laravel公共文件中,select2.min.css进入public / css文件夹,select2.min.js进入public / js文件夹并且我想在我的页面上进行多项选择。 这是我的“选择”,如:

 @foreach($tags as $tag) id }}'>{{ $tag->name }} @endforeach * 

这是我的部分:

    $(document).ready(function(){ $(".js-example-basic-multiple").select2(); });  

我不知道多重选择不起作用,浏览器总是显示“Uncaught TypeError:$(…)。select2不是函数”

以前大家都遇到过这个问题吗?

最可能的原因是加载jQuery两次。 jQuery加载时第二次删除已注册的插件。

解决方案是

  1. 脚本加载应按更正顺序排列。 那是

     1. jQuery, 2. select2, 3. your js files 
  2. jQuery应该只加载一次。

在你无法控制标签排序的情况下,或者jQuery加载两次,例如你是一个内容编辑器:

 // Concept: Render select2 fields after all javascript has finished loading var initSelect2 = function(){ // function that will initialize the select2 plugin, to be triggered later var renderSelect = function(){ $('section#formSection select').each(function(){ $(this).select2({ 'dropdownCssClass': 'dropdown-hover', 'width': '', 'minimumResultsForSearch': -1, }); }) }; // create select2 HTML elements var style = document.createElement('link'); var script = document.createElement('script'); style.rel = 'stylesheet'; style.href = 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css'; script.type = 'text/javascript'; script.src = 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.full.min.js'; // trigger the select2 initialization once the script tag has finished loading script.onload = renderSelect; // render the style and script tags into the DOM document.getElementsByTagName('head')[0].appendChild(style); document.getElementsByTagName('head')[0].appendChild(script); }; initSelect2();