统一Prototype和JQuery的$函数

Nor*_*din -1 javascript jquery conflict prototypejs

是否有任何JavaScript函数可以从Prototype和jQuery统一$函数?

是的,这是我现在面临的真实用例.我发现Prototype中的$ function和jQuery中的$相互冲突.我知道我们可以通过jQuery.noConflict()将$重新设置回Prototype,但是通过这样做,我将不得不重写使用该$函数的特定于jquery的javacript代码,或者在代码块中具有特定的jquery(例如.匿名函数).

有没有更简单的方法,无需重写两个库中的现有代码并将它们放在一个页面中?

可以回答此问题的代码可能如下所示,我们非常感谢您的反馈:

<script type="text/javascript" src="/path/to/prototype.js"></script>
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
var $j = jQuery.noConflict();
var $p = $; // reference to prototype's $
var $ = function(E, F){
  var isJQuery = true;

  //TODO: logic to determine which $ to use here YOUR SUGGESTION HERE ;-)

  var result = null;
  if(isJQuery){
    result = $j(E, F);
  } else { // prototype
    //TODO: code to delegate prototype $
  }

  return result;
}
/* ]]>*/
</script>

// ... any existing javacode jQuery and Prototype using $ function. 
Run Code Online (Sandbox Code Playgroud)

谢谢.

更新:重写问题要更清楚.

giz*_*zmo 6

好吧,首先,我很少能找到有用的情况,其中两个库都必须包含在同一页面中.所以你可以考虑删除一个.
我想这是由于插件的使用,但看看对手的插件列表,我很确定有另一种选择.

其次,对于你的jQuery特定代码,使用匿名函数技巧重写它很容易:

(function($){
  ... your code here ...
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

这将适用于大多数情况下您没有放置全局变量或方法而不是将它们绑定到事件.