1

ベースのjQueryセレクターをオーバーライドして、、などを含む任意のjQueryセレクターのすべてのCSSクラス()の前に「名前空間」を付けることを検討してい$('.classname')ます。上記の例では、私のjQueryコードは、のようになりますが、これはに変換されます。.find(.classname).parents(.classname)$('.classname')$('.SomeCssNamespace_classname')

セレクターが一致するHTMLは次の$('.classname')ようになります。
<div class="SomeCssNamespace_classname" />

regex最も重要なことは、IDやタグセレクターではなく、クラス名に対してのみこれを行うスマートを、おそらくの形式で追加する必要があるということです。たとえば$('#someId')、に翻訳されません$('#SomeCssNamespace_someId')

さらに、同じ名前空間を付加するには、メソッドjQuery.addClass()jQuery.removeClass()メソッドをオーバーライドする必要があります。

4

2 に答える 2

2

私の解決策は、これを行うための独自の関数を作成することです...例:

prefixClassSelector = function(prefix,class_name) {
    return $('.' + prefix + '_' + class_name);
}

それからあなたはそれをこのように呼ぶことができます、そしてそれはまだ連鎖可能です

prefixClassSelector('someNamespace','myclass').hide();
于 2012-09-20T17:18:55.310 に答える
0

次のようなものを試してください。

// 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;
  }
}

警告:私はこれをコンソールに貼り付けることによってのみテストし、クロムでのみテストしました。予期しない動作が発生する可能性があります。

jqueryをロードした直後にこれを実行して、他のプラグインに名前空間を付けることができるようにするのが最善です。

jQuery.fn.initコードが行うことは、関数をクラス名のプレフィックスを付ける変更されたバージョンに置き換えることです。を呼び出すと、jQuery.fn.init関数が実行されます$(selector)。同様の方法で変更addClassします。removeClass

于 2012-09-21T05:30:10.170 に答える