當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


JQuery jQuery.sub()用法及代碼示例

用法
jQuery.sub() => jQuery

版本已棄用:1.7,已刪除:1.9

說明:創建一個新的 jQuery 副本,其屬性和方法可以在不影響原始 jQuery 對象的情況下進行修改。

  • 添加的版本:1.5jQuery.sub()

    • 此方法不接受任何參數。

注意:這個 API 在 jQuery 1.9 中被移除了。

有兩個特定的用例創建了 jQuery.sub()。第一個是提供一種在不完全破壞原始方法的情況下覆蓋 jQuery 方法的輕鬆方式,另一個是幫助對 jQuery 插件進行封裝和基本命名空間。

請注意,jQuery.sub() 不會嘗試進行任何形式的隔離——這不是它的意圖。 jQuery 子版本上的所有方法仍將指向原始 jQuery(綁定和觸發的事件仍將通過主 jQuery,數據將通過主 jQuery 綁定到元素,Ajax 查詢和事件將通過主 jQuery 等)。

請注意,如果您希望將其用於插件開發,您應該首先強烈考慮使用管理狀態和插件sub-methods的jQuery UI小部件工廠之類的東西。使用 jQuery UI 小部件工廠的一些示例構建一個插件。

通過一些示例可以最好地說明此方法的特定用例。

例子:

向 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 方法以提供新函數。

(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 ).on( "remove", function( event ) {
      $( event.target ).parent().hide();
    });
  });
})();
 
// Regular jQuery doesn't trigger a remove event when removing an element
// This functionality is only contained within the modified 'myjQuery'.

創建一個返回 plugin-specific 方法的插件。

(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!
});

相關用法


注:本文由純淨天空篩選整理自jquery.com大神的英文原創作品 jQuery.sub()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。