首頁  >  工具  > $.sub()

返回值:jQuery jQuery.sub()

V1.5 概述

可建立一個新的jQuery副本,不影響原有的jQuery對像。

有兩個具體使用jQuery.sub()建立案例。首先是提供完全沒有破壞jQuery原有一切的方法,另一個用於幫助做jQuery外掛封裝和基本名稱空間。

請注意,jQuery.sub()不會做任何特殊的隔離 - 這不是它的意圖。所有關於jQuery的sub'd版本的方法將仍然指向原來的jQuery。(繫結和觸發仍將通過主jQuery的事件,資料將通過主繫結的元素的jQuery,Ajax的查詢和活動將通過主jQuery的執行,等等)。

請注意,如果你正在尋找使用這個開發外掛,應首先 認真 考慮使用一些類似jQuery UI widget工廠,這兩個狀態和外掛管理子方法。  使用jQuery UI widget的一些例子 建立一個外掛。

這種方法的具體使用情況下可以通過一些例子最好的描述。

該方法是在jQuery 1.5中引入的,但是被證明不是很有用,將被移到jQuery 1.9相容性外掛中。

示例

描述:

新增一個jQuery的方法,以便它不會受到外部分:

jQuery 程式碼:

(function(){
    var sub$ = jQuery.sub();

    sub$.fn.myCustomMethod = function(){
      return 'just for me';
    };

    sub$(document).ready(function() {
      sub$('body').myCustomMethod() // 'just for me'
    });
  })();
  
  typeof jQuery('body').myCustomMethod // undefined

描述:

改寫一些jQuery的方法,以提供新的功能。

jQuery 程式碼:

(function() {
  var myjQuery = jQuery.sub();

  myjQuery.fn.remove = function() {
    // New functionality: Trigger a remove event
    this.trigger("remove");

    // Be sure to call the original jQuery remove method
    return jQuery.fn.remove.apply( this, arguments );
  };

  myjQuery(function($) {
    $(".menu").click(function() {
      $(this).find(".submenu").remove();
    });

    // A new remove event is now triggered from this copy of jQuery
    $(document).bind("remove", function(e) {
      $(e.target).parent().hide();
    });
  });
})();

// Regular jQuery doesn't trigger a remove event when removing an element
// This functionality is only contained within the modified 'myjQuery'.

描述:

建立一個外掛,它返回外掛的具體辦法。

jQuery 程式碼:

(function() {
  // Create a new copy of jQuery using sub()
  var plugin = jQuery.sub();

  // Extend that copy with the new plugin methods
  plugin.fn.extend({
    open: function() {
      return this.show();
    },
    close: function() {
      return this.hide();
    }
  });

  // Add our plugin to the original jQuery
  jQuery.fn.myplugin = function() {
    this.addClass("plugin");

    // Make sure our plugin returns our special plugin version of jQuery
    return plugin( this );
  };
})();

$(document).ready(function() {
  // Call the plugin, open method now exists
  $('#main').myplugin().open();

  // Note: Calling just $("#main").open() won't work as open doesn't exist!
});