[英]How to use jQuery in global imported functions without jQuery.ready
my code in JS is getting very large right now and so I wanted to outsource sections to other files, for clarity.我的 JS 代码现在变得非常大,所以为了清晰起见,我想将部分外包给其他文件。
In my main file I use在我的主文件中,我使用
jQuery(document).ready(function ($) {
$.getScript("/wp-content/plugins/file2.js",function(){
console.log("loaded 2");
});
$.getScript("/wp-content/plugins/file3.js",function(){
console.log("loaded 3");
});
This works.这行得通。 In file 2 and 3 I use jQuery with functions like:在文件 2 和 3 中,我使用 jQuery,其功能如下:
function getData(){
$.("#foo").on("click", function(){});
}
So I am getting the error所以我得到了错误
$ is undefined
because I do not declare $.因为我没有声明 $. But if I wrap around the $.ready function I can't access the functions inside file 2 which are used by the other files.但是,如果我环绕 $.ready function,我将无法访问文件 2 中其他文件使用的函数。
How can I 'declare' the $ separately without loosing the global scope of the function. Or is there even a better way?如何在不丢失 function 的全局 scope 的情况下单独“声明”$。或者有更好的方法吗? I only include in html:我只包括在 html 中:
<script src="/wp-content/plugins/file1.js" type="text/javascript"></script>
Thanks for helping!感谢您的帮助!
A copy of jQuery
is assigned to $
by default . jQuery
的副本默认分配给$
。
It will only be undefined if you:只有在以下情况下才会未定义:
$.noConflict()
调用$.noConflict()
… so don't do any of those. ……所以不要做任何这些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.