我如何实现JQuery.noConflict()? [英] How do I implement JQuery.noConflict() ?

查看:132
本文介绍了我如何实现JQuery.noConflict()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在同一个html页面上使用javascript和jquery代码。出于某种原因,jQuery库阻止我的原生javascript代码正常工作。

I am using both javascript and jquery code on the same html page. For some reason, the jQuery library is stopping my native javascript code from working properly.

我找到了这个页面: jQuery No Conflict 表示你可以使用jquery.noConflict将$释放回javascript。但是,我不知道该怎么做?

I found this page: jQuery No Conflict that says you can use a jquery.noConflict to release $ back to javascript. However, I'm not sure how to do this?

具体来说,我不确定如何正确实现这一点? Jquery代码在哪里,JS代码在哪里?

Specifically, I'm not sure how to implement this correctly? Where does the the Jquery code go, where does the JS code go?

我的代码如下:

<script type="text/javascript">
  $.noConflict();
  // Code that uses other library's $ can follow here.
</script>


推荐答案

jQuery.noConflict 将重置 $ 变量,因此它不再是 jQuery 的别名。除了只召唤一次,你真的不需要做太多其他事情。但是,如果您愿意,可以使用返回值创建自己的别名:

jQuery.noConflict will reset the $ variable so it's no longer an alias of jQuery. Aside from just calling it once, there's not much else you really need to do. Though, you can create your own alias with the return value, if you'd like:

var jq = jQuery.noConflict();

一般来说,你想在包含jQuery和任何插件之后立即执行此操作:

And, generally, you want to do this right after including jQuery and any plugins:

<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript" src="/path/to/jquery-plugin.js"></script>
<script type="text/javascript">
  jQuery.noConflict();
  // Code that uses other library's $ can follow here.
</script>
<script type="text/javascript" src="/path/to/prototype.js"></script>

您还可以更进一步,释放 jQuery with noConflict(true)。虽然,如果你采取这种方式,你肯定会想要一个别名,因为 $ jQuery 可能都是什么你想要:

You can also go one step further and free up jQuery with noConflict(true). Though, if you take this route, you'll definitely want an alias as neither $ nor jQuery will probably be what you want:

var jq = jQuery.noConflict(true);

我认为最后一个选项主要用于混合jQuery版本,特别是对于过时的插件你想更新jQuery本身:

I think this last option is mostly used for mixing versions of jQuery, particularly for out-dated plugins when you want to update jQuery itself:

<script type="text/javascript" src="jquery-1.4.4.js"></script>
<script type="text/javascript" src="jquery-older-plugin.js"></script>
<script type="text/javascript">
    var jq144 = jQuery.noConflict(true);
</script>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
<script type="text/javascript" src="jquery-newer-plugin.js"></script>

这篇关于我如何实现JQuery.noConflict()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆