Javascript jQuery:没有冲突

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3188262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:36:56  来源:igfitidea点击:

jQuery: noConflict

javascriptjquery

提问by David Yell

I just cannot work this out. My god it's making my brain hurt, so I turn to you, the good people of the internet.

我就是无法解决这个问题。天哪,这让我的大脑受伤了,所以我求助于你们,互联网上的好人。

I've been staring at the documentation for the jQuery $.noConflict()functionwith no luck.

我一直在盯着jQuery$.noConflict()函数的文档,但没有运气。

My issue is that the site I'm working on already includes jQuery 1.1.3.1 but I want to do some awesome and snazzy UI work in a few places, so I want to use 1.4.2 for obvious reasons.

我的问题是我正在处理的站点已经包含 jQuery 1.1.3.1,但我想在一些地方做一些很棒和时髦的 UI 工作,所以我想使用 1.4.2,原因很明显。

I've been trying to run these side by side but I can't seem to get any code to execute. I also need to implement a few plugins using 1.4.2 so I'm not sure if putting jQuery over to something like $jwould work, as obviously the plugins would pick up $and jQueryas 1.1.3.1rather than 1.4.2.

我一直在尝试并排运行这些,但似乎无法执行任何代码。我还需要实现使用1.4.2几个插件,所以我不知道,如果把在jQuery的喜欢的东西$j会的工作,因为很明显,插件会拿起$jQuery作为1.1.3.1,而不是1.4.2

Is there a way that I can wrap my code in a noConflict()block and also include the plugins that I need to create a self contained block of 1.4.2code?

有没有一种方法可以将我的代码包装在一个noConflict()块中,并且还包括创建自包含1.4.2代码块所需的插件?

Any help would be fantastic as my poor mind weeps amid the vast wasteland that is the API docs!

任何帮助都会很棒,因为我可怜的头脑在 API 文档的广阔荒地中哭泣!

采纳答案by SLaks

You should simply upgrade the entire site to 1.4.2.
jQuery does not in general have many breaking changes, so that shouldn't be so hard.

您应该简单地将整个站点升级到 1.4.2。
jQuery 通常不会有很多重大更改,因此应该不会那么难。

回答by jamsheed

If you have two or three jQuery in the same page, just put a different variable for each different jQuery.

如果您在同一页面中有两个或三个 jQuery,只需为每个不同的 jQuery 放置一个不同的变量。

Example:

例子:

<script type="text/javascript">
    var $s = jQuery.noConflict();
    $s(document).ready(function() {
        $s('#news-container').vTicker({
            speed: 500,
            pause: 3000,
            animation: 'fade',
            mousePause: true,
            showItems: 2
        });
    });
</script>
<script type="text/javascript">
    var $j = jQuery.noConflict();
    $j(document).ready(function() {
        $j('.sf-menu ul').superfish({
            delay: 1000,
            animation: {
                opacity: 'show',
                height: 'show'
            },
            speed: 'medium',
            autoArrows: false,
            dropShadows: 'medium'
        });
    });
</script>

回答by j.strugnell

I had a similar issue recently where I was using jQuery v1.3.2 on a page but a 3rd party questionnaire popup was using an older version on the same page. I eventually managed to solve the problem. I referenced jQuery 1.3.2 as follows:

我最近遇到了类似的问题,我在页面上使用 jQuery v1.3.2,但 3rd 方问卷弹出窗口在同一页面上使用旧版本。我最终设法解决了这个问题。我引用了 jQuery 1.3.2 如下:

 <script type="text/javascript" src"/Scripts/jquery-1.3.2.min.js"></script>
    <script type="text/javascript"> 
        jq132 = jQuery.noConflict(true); 
 </script> 

I then modified all my jQuery code to use jq132 instead of $. I then did a find and replace on all of the plugins I was using to replace "$(" with "jq132(" and "$." with "jq132.". There may be a more elegant approach but this worked for me. I'm far from a jQuery expert so there may be other $ syntax that you need to handle (i.e. not just "." and "(").) .

然后我修改了我所有的 jQuery 代码以使用 jq132 而不是 $。然后我做了一个查找和替换我用来替换“$(”与“jq132(”和“$。”与“jq132。”的所有插件。可能有更优雅的方法,但这对我有用。我远非 jQuery 专家,因此您可能需要处理其他 $ 语法(即不仅仅是 "." 和 "(").) 。

回答by Drew Wills

You should post an example that isn't working. I bet we'd clear it up immediately.

您应该发布一个不起作用的示例。我敢打赌我们会立即清理它。

I don't believe noConflict is a 'block' exactly. You use noConflict to tell jQuery that you want it to remove anything it declares from the global JavaScript namespace (because you want to load jQuery again and reuse those names).

我不相信 noConflict 是一个“块”。您使用 noConflict 告诉 jQuery 您希望它从全局 JavaScript 命名空间中删除它声明的任何内容(因为您想再次加载 jQuery 并重用这些名称)。

On a page with more than 1 instance of jQuery loaded, bothinstances should use noConflict. I don't know if it's possible to load a second instance of jQuery if there's already an instance loaded and that instance didn't call noConflict.

在加载了 1 个以上 jQuery 实例的页面上,两个实例都应使用 noConflict。如果已经加载了一个实例并且该实例没有调用 noConflict,我不知道是否可以加载第二个 jQuery 实例。

@SLaks and @galambalazs: Sometimes you're writing a small amount of content that will be displayed within a larger page, such as a portal. The portal already uses a(n outdated) version of jQuery, but you need a newer version. Also you don't control the larger portal page, just the content you're writing that will be displayed within it.

@SLaks 和@galambalazs:有时您正在编写少量内容,这些内容将显示在更大的页面(例如门户)中。该门户网站已经使用了一个(n 过时)版本的 jQuery,但您需要一个更新的版本。此外,您无法控制更大的门户页面,而只能控制您正在编写的将显示在其中的内容。

This scenario accurately describes real work I do commonly.

这个场景准确地描述了我经常做的实际工作。

回答by droo

I would agree with other posts that suggest trying to upgrade to 1.4.2 across the board... That said, you clearly have a good reason for attempting what you are trying to do. To my knowledge there is no easy way to deal with your situation (as I too have tried something similar).

我同意其他建议尝试全面升级到 1.4.2 的帖子......也就是说,您显然有充分的理由尝试您正在尝试做的事情。据我所知,没有简单的方法可以处理您的情况(因为我也尝试过类似的方法)。

"noConflict" simply releases the global "$" variable so that other libraries/scripts may safely use it. Given that you are trying to use two versions of jQuery "noConflict" isn't really helpful here...calling it for both versions of jQuery doesn't change the fact that both versions still need to reference the global "jQuery" object (of which there can only be one...).

"noConflict" 只是释放全局 "$" 变量,以便其他库/脚本可以安全地使用它。鉴于您正在尝试使用两个版本的 jQuery“noConflict”在这里并没有真正的帮助......为两个版本的 jQuery 调用它不会改变两个版本仍然需要引用全局“jQuery”对象的事实(其中只能有一个......)。

The issue (as you clearly already know) is that loading the 2nd jQuery version will "clobber" the original jQuery object (and all the "customizations" made to it by plug-ins).

问题(您已经清楚地知道)是加载第二个 jQuery 版本将“破坏”原始 jQuery 对象(以及插件对其进行的所有“自定义”)。

The only reliable (albeit incredibly inefficient) solution I could come up with is:

我能想出的唯一可靠(尽管效率极低)的解决方案是:

  • Load the existing (old) jQuery version and plugins (assuming you can't avoid this)
  • Load the new jQuery version
  • RE-load and existing plugins and any new plugin you want to use
  • Test extensively
  • 加载现有(旧)jQuery 版本和插件(假设您无法避免这种情况)
  • 加载新的 jQuery 版本
  • 重新加载和现有插件以及您要使用的任何新插件
  • 广泛测试

回答by gblazex

A solid advice: don't stress your and your visitors bandwidthwith two jQuery versions. Change your whole codebase to the latest version. It's got less bugs, more supportand improved behavior.

一个可靠的建议:不要用两个 jQuery 版本来强调您和您的访问者的带宽。将整个代码库更改为最新版本。它有更少的错误,更多的支持和改进的行为。

回答by klaus

WAY late .... but might help someone - threw this together.

太晚了......但可能会帮助某人 - 把它放在一起。

/**
*********************************************************************************************************
*           jQuery version check
*           $.noConflict() is not enough to ensure jQuery as well as $ 
*           has correct version (can cause troubles with jQuery plugins that use fn(){}(jQuery);
*
*           useage: restoreJquery('1.10.2',true) //for unminimized dev version
*                   restoreJquery('1.10.2')          //for minimized version
*                   restoreJquery('1.10.2',true,myFunction)          //for minimized version, that executes a function once jQuery is in the page
*
*
**/

function restoreJquery(wantedVersion,devVersion,callback) {
    if(!wantedVersion){
        wantedVersion= '1.10.2';
    }

    //is current jQuery version ===wanted version? (double check to avoid undefined errors)
    if($ && $.fn.jquery!==wantedVersion){                

        //if not invoke noConflict with true (true=gives up the jQuery name space aswell as $)
        var $jQuery = jQuery.noConflict(true); 
        //Line Assign the new object to new instantiated versions of jQuery
        var $=jQuery=$jQuery;                          
      }

    //if jQuery is still not the correct version inject it into page via plain vanilla js

    //if $ does not exist or the version is wrong inject it into the page
    if(!$ || $.fn.jquery!==wantedVersion){ 

        var head=document.getElementsByTagName('head')[0], //get Head
            jqPath=wantedVersion+'jquery.', // ex '1.10.2/jquery.
                    script=document.createElement('script'); //create empty scripttag

            if(devVersion){  //minimized or not?
                jqPath+='min.js';
            }else{
                jqPath+='js';
            }

        script.src='//http://ajax.googleapis.com/ajax/libs/jquery/'+jqPath; //create src path
        script.type='text/javascript'; //add type
        script.async=true; //set async to true
        //real browsers
        script.onload=callback;  //call callback on load

        //Internet explorer doesnt support onload on script (typical ie)
        script.onreadystatechange = function() {
            if (this.readyState == 'complete') {
                callback();
            }
        }


    head.appendChild(script);

    }else{
        //otherwise call the callback since noConflict solved our jQuery versioning issues
        callback();
    }

};

回答by Srikrushna

jQuery no-conflict is an option given by jQuery team to overcome the conflicts between the different JS frameworks or libraries. We are replacing the $ to a new variable and assigning to jQuery when we use the noconflict method.

jQuery no-conflict 是 jQuery 团队提供的一个选项,用于克服不同 JS 框架或库之间的冲突。当我们使用 noconflict 方法时,我们将 $ 替换为一个新变量并分配给 jQuery。

    <button>Test jQuery noConflict</button>
    <script>
        var newjq = $.noConflict();
        newjq(document).ready(function(){
           newjq("button").click(function(){
               newjq("p").text("Wahh..! Its working!");
            });
        });
    </script>

We can use the $ sign like below also, it not create any conflict also

我们也可以使用像下面这样的 $ 符号,它也不会产生任何冲突

$.noConflict();
jQuery(document).ready(function($) {
   // Code that uses jQuery's $ can follow here.
});