尝试这样的事情:
// define the namespace
jQuery.myjQueryNamespace = {
name: 'custom_', // the prefix
// returns the prefixed selector, classname needs to be prefixed with "."
addNamespace: function(selector) {
if (typeof String.prototype.indexOf == "function") {
return selector.replace(/\./g, '.' + jQuery.myjQueryNamespace.name);
} else {
// TODO: write my own indexOf function
return selector;
}
},
// returns the prefixed selector, classname should *not* to be prefixed with "."
prefixNamespace: function(selector) {
return jQuery.myjQueryNamespace.name + 'selector';
}
}
// keep the original init function
jQuery.fn._init = jQuery.fn.init;
jQuery.fn.init = function(selector, context, rootjQuery) {
if (typeof selector == 'string'
&& typeof String.prototype.indexOf == "function" // assumes String.prototype.indexOf is defined
&& selector.indexOf('.') != -1) {
var myNewSelector = jQuery.myjQueryNamespace.addNamespace(selector);
return jQuery.fn._init.call(this, myNewSelector, context, rootjQuery);
} else {
return jQuery.fn._init.call(this, selector, context, rootjQuery)
}
}
// *got this from the jQuery source code
jQuery.fn.init.prototype = jQuery.fn;
// modify addClass and removeClass
for (var fn_key in jQuery.fn) {
// if the function has "Class" in it, replace the function
if (fn_key == 'addClass' || fn_key == 'removeClass') {
// we'll keep the original function prefixed with underscore
jQuery.fn['_' + fn_key] = jQuery.fn[fn_key];
// build the new function which calls the original function passing in the namespaced selector
var new_function = new Function("selector", "return jQuery.fn['" + '_' + fn_key + "'].call(this, jQuery.myjQueryNamespace.prefixNamespace(selector));");
// assign it to the original name
jQuery.fn[fn_key] = new_function;
}
}
警告:我只通过粘贴到控制台中进行了测试,并且仅在 chrome 中。它可能有意想不到的行为。
最好在加载 jquery 后立即运行它,允许其他插件被命名空间。
代码所做的是将jQuery.fn.init
函数替换为以类名为前缀的修改版本。该jQuery.fn.init
函数在您调用时运行$(selector)
。我们以类似的方式进行addClass
修改。removeClass