TypeError: $(…).select2 不是 jQuery 中的函数
TypeError: $(…).select2 is not a function in jQuery
“$(…).select2 is not a function” jQuery 错误的发生有多种原因:
- 忘记包含 select2 库。
- 在 jQuery 库之前加载 select2 库。
- 加载 jQuery 库两次。
- 指定了错误的 jQuery 文件路径。
要解决“$(…).select2 不是函数”jQuery 错误,请确保在加载 select2 库之前加载 jQuery 库。
这些库只能在页面上加载一次,否则会抛出错误。
<!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.
$(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 should be loaded:
- Load the jQuery script.
- Load the Select2 script.
- 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.
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.
这些库只能在页面上加载一次,否则会抛出错误。