【问题标题】:Example of using jQuery noConflict on 2 jQuery plugins在 2 个 jQuery 插件上使用 jQuery noConflict 的示例
【发布时间】:2015-10-18 00:33:49
【问题描述】:

我正在寻找一个 jQuery noConflict 示例,该示例在同一代码 sn-p 中显示 2 个 jQuery 插件以及如何使用 jQuery.noConflict 以便这些插件应该起作用。在下面的场景中它会应用在什么地方?

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://example.com/jquery.plugin_1.js"></script>
<script type="text/javascript" src="http://example.com/jquery.plugin_2.js"></script>

<script type="text/javascript">    
$(document).ready(function() {
    // plugin_1 code...
}
</script>

<script type="text/javascript">    
$(document).ready(function() {
    // plugin_2 code...
}
</script>

【问题讨论】:

  • 没有 noConfict ,你的代码能工作吗?
  • 不,我正在运行一个实现 jQuery 和各种插件的 Joomla 站点。每当我引入自定义 jQuery 插件时,新插件都无法工作,除非我实施了不正确的解决方法(例如,在新插件使用之前重新调用相同的 jquery 文件)
  • 看看链接stackoverflow.com/questions/7882374/…有没有帮助!
  • noConflict 的目的是允许 jQuery 与另一个使用 $ 作为函数或变量名的库一起运行,它并不是为了解决 jQuery 插件之间的冲突。
  • 哦!现在我明白了。好吧,我在下面的回答仍然允许我的插件最终工作,因为它们现在可以正确地避免与使用 $ 的任何其他库的冲突。

标签: javascript jquery html


【解决方案1】:

jQuery noConflict 的这个应用程序对我有用:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://example.com/jquery.plugin_1.js"></script>
<script type="text/javascript" src="http://example.com/jquery.plugin_2.js"></script>

<script type="text/javascript">
var $plugin_1 = jQuery.noConflict();
$plugin_1(document).ready(function() {
    // replace "$" with "$plugin_1" in all instances of its use here.
    // plugin_1 code...
}
</script>

<script type="text/javascript">
var $plugin_2 = jQuery.noConflict();
$plugin_2(document).ready(function() {
    // replace "$" with "$plugin_2" in all instances of its use here
    // plugin_2 code...
}
</script>

【讨论】:

    【解决方案2】:

    大多数 Joomla 安装还捆绑了 MooTools,它使用 $$$ 以及使用 $ 的 jQuery。这听起来像您遇到的问题。但是,这两个框架也都有自己可以使用的全局变量。 对于 MooTools,它是 document.id,对于 jQuery,它是 jQuery。 作为一般规则,闭包有助于解决插件的兼容性问题。 你可以选择使用闭包来修复插件,或者用它们包裹你的$(document).ready()。我个人两者都做。

    jQuery https://api.jquery.com/jquery.noconflict/

    (function($){
       //jQuery code here
    }(jQuery));
    

    MooTools http://mootools.net/blog/2009/06/22/the-dollar-safe-mode

    (function($){
       //MooTools code here
    }(document.id));
    

    许多全局值/变量可能会出现同样的问题,例如使用某些插件覆盖 undefined。

    var undefined = null;
    var isDefined = (typeof myVar === undefined);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 2016-11-14
      相关资源
      最近更新 更多