返回介绍

jQuery.sub()

发布于 2017-09-11 17:02:43 字数 2936 浏览 1264 评论 0 收藏 0

所属分类:核心 API | 弃用 > 1.7 版本弃用的 API | 已删除的函数

jQuery.sub()返回: jQueryversion deprecated: 1.7, removed: 1.9

描述: 可创建一个新的jQuery副本,其属性和方法可以修改,而不会影响原来的jQuery对象。

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

    • 这个方法不接受任何参数。

这种方法在jQuery1.7已经被过时了,在jQuery 1.8版本将被移动到一个插件中。

有两个具体使用jQuery.sub()创建jQuery副本的案例。第一种情况是希望重写 jQuery 的方法,而不想破坏原始的方法。另一种情况是想为 jQuery 插件做进一步的封装或进行基本的命名空间。

注意,jQuery.sub() 并不尝试做任何形式的隔离,因为这不是该方法的本意。所有 jQuery 副本中的方法依然指向原始的 jQuery (例如,依然会通过原始的 jQuery 进行事件绑定和触发,data 也会通过原始的 jQuery 绑定到元素上。Ajax 请求和事件也是通过原始的 jQuery 运行的等等。)。

请注意,如果你正在寻找使用这个开发插件,应首先认真考虑使用一些类似jQuery UI widget工厂,这两个状态和插件管理子方法。 使用jQuery UI widget的一些例子建立一个插件。

上述那些例子非常好的描述了该方法的详细用法。

例子:

Example: 添加一个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

Example: 重写一些 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'.

Example: 创建一个插件,返回插件的具体方法。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文