开发者

Make jQuery no conflict

I am creating a web widget to be posted on other websites. In the widget it will call jQuery and I dont want the jQuery to conflict with other JavaScript libraries that the website may have installed. When I load the jQuery I would like to call jQuery like this:

JQuery_MYSite('id').find('selector');

I found out if I do this then $ will not be able to be used even if the other website uses $.


When the widget loads it find out if jQuery is loaded. If so, then it will use the $ to call jQuery. But I know $ is not unique to just jQuery - other javas开发者_开发百科cript libraries use it. So how can I use my own jQuery prefix with without interfering with the website owners prefix.


In the widget it will call jQuery and I dont want the jQuery to conflict with other JavaScript libraries that the website may have installed.

I don't think you can achieve this, because jQuery.noConflict() must be called after the other scripts have been loaded. So, if there is no way for you to know about the other scripts, then you won't have a way to avoid the conflicting.

When the widget loads it find out if jQuery is loaded. If so, then it will use the $ to call jQuery. But I know $ is not unique to just jQuery - other javascript libraries use it. So how can I use my own jQuery prefix with without interfering with the website owners prefix.

Wrap your widget code with an auto-executing anonymous function:

(function($){

// your widget code here
// $ will always be jQuery

})(jQuery);


var myJquery = jQuery.noConflict();

then if you want to get fancy:

(function($){
    $(".whatever").doSomeStuff();
})(myJquery);


use noConflict

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


Check out jQuery.noConflict().


look at noConflict

$.noConflict();
(function($){
   // $ is jQuery here
})(jQuery);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜