简体   繁体   English

jQuery范围与wordpress中的noconflict

[英]jQuery scope with noconflict in wordpress

I'm bringing a template across from an old version of Joomla into Wordpress and got quite a few javascript files that I have to use with the main referring out to functions in the others. 我将一个旧版Joomla的模板带到了Wordpress中,得到了一些我必须使用的javascript文件,主要用于引用其他文件中的函数。 All of these files use jQuery left right and centre and given Wordpress uses noconflict by default I thought it would be straightforward to wrap each js file up like this: 所有这些文件都使用jQuery左右和中心,并且默认情况下Wordpress使用noconflict我认为将每个js文件包装起来就像这样简单:

(function($){
....my code...
})(jQuery);

The problem I get is with the scope of functions that are called across files, so for example: 我得到的问题是跨文件调用的函数范围,例如:

File 1 档案1

(function($){
    $(document).ready(function(){
        mainmenu();
    });
})(jQuery);

File 2 档案2

(function($){
    function mainmenu(){
        alert("hello");
    }
})(jQuery);

Here is the problem I get the error "uncaught ReferenceError: mainmenu is not defined", I know it will be something simple to reference the function, but I can't see it, probably be a "Doh" moment. 这是我得到错误的问题“未捕获的ReferenceError:mainmenu未定义”,我知道引用该函数会很简单,但我看不到它,可能是一个“Doh”时刻。 Any help is most appreciated. 任何帮助都非常感谢。 Yes I know I could just find and replace the '$' with 'jQuery' but I just thought that there must be a way to do it? 是的我知道我可以找到并用'jQuery'替换'$',但我只是觉得必须有办法做到这一点?

it is because the mainmenu is a closure function within the anonymous function in the second file.. so it is not available in file1. 这是因为mainmenu是第二个文件中匿名函数内的闭包函数..所以它在file1中不可用。

One possible solution is to make it a global function, so that it will be available in the global scope. 一种可能的解决方案是使其成为一个全局函数,以便它可以在全球范围内使用。

(function($){
    window.mainmenu = function (){
        alert("hello");
    }
})(jQuery);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM