开发者

jQuery - function conflicts

I have a WordPress theme and I'm using a few jQuery plugins within it. The problem is that some of these plugins are included in other WP plugins, so the js breaks because of naming conflicts.

I was wondering if there is a way to somehow isolate a set of functions or a .js file from the rest of the scripts that are being included in the HTML document.

something like:

function wrap(){

  plugin functions...
  plugin functions...

}

jQuery(d开发者_开发问答ocument).ready(function($){
   wrap.pluginfunction()...
   wrap.pluginfunction()...
});


The easiest way to do this is to wrap the whole script like this:

var someNewNamespace = (function () {
    // Script goes here

    // If you want to expose functions on the namespace:
    var that = {};

    // Declare a new function to expose:
    that.someFunction = function () {
        // ...
    };

    // Expose a function declared previously:
    that.someOtherFunction = someFunctionDeclaredPreviously;

    return that;
}();

This will effectively create a new namespace for the script. The someNewNamespace object will have members like someFunction etc. after this executes. Any variables declared within the anonymous outer function, but not exposed via the that object will be inaccessible from outside of the script.


jQuery has a noConflict() method so it won't kill other libraries.

Just call jQuery.noConflict(); after loading the jquery library and you should be set.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜