如何使用jQuery无冲突模式和多个脚本位置
多么糟糕的头衔。 也许有人可以为我编辑它。 这是独家新闻:
我需要在jQuery无冲突模式下工作,但我仍然想利用$快捷方式,所以我的所有函数等都在(function($){ ... })(jQuery);
的典型闭包中定义(function($){ ... })(jQuery);
所有这些都在外部source.js文件中定义,该文件包含在我的HTML网页的顶部。
稍后,我需要添加一些内联 ,它使用我在闭包中定义的一个实用函数。 显然,我已将自己命名为一个框,无法访问该function。
这里使用的模式是什么?
要控制在全局命名空间中显示的内容和内容,可以自定义通过一个全局对象(通常以全部大写字母)显示所需内容。
FOO.module1.init(); FOO.module2.init();
您可以通过确保FOO存在来实现此目的,如果不存在:创建它。
var FOO = this.FOO || {};
模块命名空间也是如此:
FOO.module1 = FOO.module1 || {};
然后在匿名函数内部,暴露你想要的东西。
完整的例子
module1.js:
var FOO = this.FOO || {}; FOO.module1 = FOO.module1 || {}; (function ($) { var my, local, data; function init() { // use my, local and data here. } FOO.module1.init = init; }(jQuery));
module2.js:
var FOO = this.FOO || {}; FOO.module2 = FOO.module2 || {}; (function ($) { var some, other, data; function init() { // use some, other and data here. } FOO.module2.init = init; }(jQuery));
controller.js:
FOO.module1.init(); FOO.module2.init();
Magnar的答案是找到任何复杂的方法。 但只是为了完整起见,对于非常简单的事情,你可以像这样使它全局化:
$.noConflict(); (function($){ window.doSomething = function(){ $("body").css("background-color","red"); } })(jQuery); doSomething();
通过向window
添加函数,它变为全局。