jQuery noConflict

问题描述:

在这个简单的示例中:

var myFunction = function(obj) {
    console.log($(obj));
}

我正在使用$.如果我使用:

I am using the $. If I use:

jQuery.noConflict();
var myObj = {X:1};
myFunction(myObj);

然后$不再有效.

但是如果我将myFunction包装在其中

But if I wrap myFunction inside of

jQuery(function($) {
var myFunction = function(obj) {
    console.log($(obj));
}
});

然后不再找到. myFunction是在单独的脚本中,因此我无法将所有内容都包装在一个巨大的jQuery(function($){}中.

Then it's no longer found. myFunction is in a separate script, so I can't wrap everything in one gigantic jQuery(function($) {}.

尝试一下:

( function($) {
  window.myFunction = function(obj) {
    console.log($(obj));
  }
})(jQuery);

单独的文件:

myFunction({X:1});

区别在于您的代码不会在dom准备就绪后立即执行,而是将函数放置在全局上下文(窗口)中,因此它将随处可见.

The difference is that your code is executed immediately not after the dom is ready and you are placing the function in the global context (window.) so it will be available everywhere.

我不知道您在做什么,但是在这种情况下,您可能会发现一个更适合您的JQuery插件:

I don't know what it is your doing, but in this case you may find a JQuery plugin suits you better:

( function($) {
  $.fn.myFunction = function(obj) {
    console.log(this);
  }
})(jQuery);

单独的文件:

jQuery({X:1}).myFunction();

当然,$({X:1})可能会对JQuery做一些奇怪的事情-我以前从未尝试过!

Of course, $( {X:1} ) might do strange things with JQuery - I've never tried it before!