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

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

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

“$(…).on if not a function”jQuery 错误的发生有两个主要原因:

  1. 加载不支持该on
    功能的旧版本 jQuery 库。
  2. 加载覆盖美元符号$变量值的库。

这是一个工作示例,展示了如何on在 jQuery 中使用该函数。

索引.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <!-- ✅ load jQuery ✅ --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous" ></script> </head> <body> <button id="btn">Click</button> <script src="index.js"></script> </body> </html>

我们加载了最新版本的 jQuery 库并定义了一个按钮,我们将向其添加事件侦听器。

这是该index.js文件的代码。

索引.js
$(document).ready(function () { $('#btn').on('click', function () { console.log('Button clicked'); }); });

If you load the page and click on the button, you will see the console.log
output printed to the console.

The on() function requires jQuery version 1.7 or newer.

If you are loading a script that overrides the value of the dollar sign
variable, use the jQuery global instead.

index.js
jQuery(document).ready(function () { jQuery('#btn').on('click', function () { console.log('Button clicked'); }); });
This issue might occur if you load a script that overrides the value of the global dollar sign variable after you have loaded the jQuery script.

Loading multiple scripts that override the same global variable can be quite
confusing because the script that is run last wins.

Conclusion #

要解决“$(…).on if not a function”jQuery 错误,请确保加载最新版本的 jQuery 库并检查是否包含任何覆盖全局美元符号$
变量值的脚本
加载 jQuery 脚本后。