我希望覆盖基本的命名空间选择器,以便任何jQuery选择器中的所有CSS类( $('.classname') ),包括.find(.classname)、.parents(.classname)等,都以‘jQuery’为前缀。在上面的示例中,我的jQuery代码看起来像$('.classname'),但它将被转换为$('.SomeCssNamespace_classname')。
$('.classname')选择器将匹配的超文本标记语言如下所示:
<div class="SomeCssNamespace_classname" />
最重要的是,我将不得不添加智能,可能是以regex的形式,它只对类名执行此操作,而不是id或标签选择器。例如,$('#someId')不会被翻译成$('#SomeCssNamespace_someId')。
此外,必须重写jQuery.addClass()和jQuery.removeClass()方法才能预置相同的命名空间。
发布于 2012-09-21 01:18:55
我的解决方案是编写你自己的函数来做这件事。例如:
prefixClassSelector = function(prefix,class_name) {
return $('.' + prefix + '_' + class_name);
}然后你可以这样调用它,它仍然是可链接的
prefixClassSelector('someNamespace','myclass').hide();发布于 2012-09-21 13:30:10
尝试如下所示:
// 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函数替换为添加了类名前缀的修改后的版本。当您调用$(selector)时,会运行jQuery.fn.init函数。我们以类似的方式修改addClass和removeClass。
https://stackoverflow.com/questions/12517013
复制相似问题