【问题标题】:When should I use $.fn.extend() in jQuery? [closed]什么时候应该在 jQuery 中使用 $.fn.extend()? [关闭]
【发布时间】:2013-12-27 13:29:09
【问题描述】:

我是 jQuery 的新手。一些 jQuery 插件使用 $.fn.extend(),我在 jQuery api 文档中看到过,但我不明白什么时候应该使用它或如何使用它。

我在插件skitter-slider 中看到了它。我真的很想知道如何使用它。

如果有人可以帮助我,我将不胜感激。提前谢谢你。

【问题讨论】:

  • 你看文档了吗:api.jquery.com/jQuery.fn.extend
  • jquery plugin $.extend的可能重复
  • 提示:学习如何使用Stack Overflow,很简单:help center
  • @Yogesh,是的,我读过它,但在这一行:“jQuery.fn.extend() 方法扩展了 jQuery 原型 ($.fn) 对象以提供可以链接到jQuery() 函数。”,我迷路了。
  • 该行的哪一部分让您感到困惑?你了解什么是 JavaScript 原型吗?

标签: javascript jquery


【解决方案1】:

我什么时候使用它以及如何使用它

当您想要合并对象时。例如你有

var A = {
   foo: 42
};

var B = {
   bar: 21;
};

现在您想将B 合并到A,以创建

var A = {
   foo: 42,
   bar: 21
};

这是由

$.extend(A, B);

【讨论】:

  • 我知道如何使用 $.extend() 但我的问题是如果我创建 OOP jQuery 插件如何使用 jQuery.fn.extend
  • 也许您应该编辑您的问题并正确解释您的问题。还包括一些示例代码。仅供参考,$.extend$.fn.extend 是同一个功能。
  • 使用 $.extend 我们可以合并 2 个函数,使用 $.fn.extend 我们可以做同样的事情...我明白了,谢谢!
  • 对象,而不是函数。
  • 当我应该使用 $.fn.extend 而不是 $.extend 时,您有可以帮助我的链接或示例吗?
【解决方案2】:

例如,如果您有任何带有配置的插件,您可以设置默认值并用 $.extend 对其进行补充

看看这个:

(function ($) {

    $.superPlugin = {

        // plugin defaults
        defaults: 
        {
            mainClass: 'node',
            orientation: 'vertical',
            focusEvent: function (event) {
                console.log('Focus!');
            }
        };
    };

    // plugin code
    $.fn.superPlugin = function (fn, options) {

        var config = $.extend( true, {}, $.setSelect.defaults, options );

        /**
         *  results: { 
         *      mainClass: 'node', 
         *      orientation: 'horizontal', 
         *      focusEvent: function (event) {
         *         console.log('Custom focus event!');
         *      }
         *  }
         */
    };

})(jQuery);

// custom config
var options = {
    orientation: 'horizontal',
    focusEvent: function (event) {
        console.log('Custom focus event!')
    }
}

// bind plugin to element
$('.item').superPlugin(options);

【讨论】:

  • 这是一个很好的例子,但无法解释其中的区别
猜你喜欢
  • 2017-09-11
  • 1970-01-01
  • 2012-12-23
  • 2021-07-13
  • 2011-01-29
  • 2022-01-02
  • 2011-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多