类型错误:$(…).select2 不是 jQuery 中的函数

TypeError: $(…).select2 不是 jQuery 中的函数

TypeError: $(…).select2 is not a function in jQuery

“$(…).select2 is not a function” jQuery 错误的发生有多种原因:

  1. 忘记包含 select2 库。
  2. 在 jQuery 库之前加载 select2 库。
  3. 加载 jQuery 库两次。
  4. 指定了错误的 jQuery 文件路径。

要解决“$(…).select2 不是函数”jQuery 错误,请确保在加载 select2 库之前加载 jQuery 库。

这些库只能在页面上加载一次,否则会抛出错误。

索引.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <!-- ✅ Load CSS file for Select2 --> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <!-- ✅ load jQuery ✅ --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous" ></script> <!-- ✅ load JS for Select2 ✅ --> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous" referrerpolicy="no-referrer" ></script> </head> <body> <!-- 👇️ Select menu --> <select class="basic-single" name="state"> <option value="AL">Alabama</option> <option value="WY">Wyoming</option> </select> <!-- ✅ Your JS script here ✅ --> <script src="index.js"></script> </body> </html>

Note that we loaded the JavaScript code for the select2 library after loading
the jQuery library, but before running our code that’s located in the index.js
file.

Here is the code in the index.js file.

index.js
$(document).ready(function () { $('.basic-single').select2(); });

In the index.js file, we make sure the DOM is ready before initializing the
Select2 menu. You only need a single $(document).ready() block per page.

If you load the page you will see the select menu.

The order in which the scripts are loaded is very important because they rely on one another. Make sure to load the jQuery script first, then the Select2 script and lastly load your JS script.

The order in which the scripts should be loaded:

  1. Load the jQuery script.
  2. Load the Select2 script.
  3. Load your personal JS script (e.g. index.js).

If you still get the error you might be loading the jQuery library twice.

Loading the library twice re-runs the initialization process and causes the
error.

If you are loading the libraries from files on your local file system, make sure to specify the paths to the files correctly. Specifying an incorrect path to a script is equivalent to not loading the script at all.

You can check if you’re loading the scripts correctly by opening your Developer
tools by pressing F12 and clicking on the Console tab.

If you see any 404 errors related to loading the jQuery scripts, then the path
to the file is incorrect.

Conclusion #

To solve the “$(…).select2 is not a function” jQuery error, make sure to
load the jQuery library before loading the select2 library.

这些库只能在页面上加载一次,否则会抛出错误。