当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。