扩展现有的jQuery函数

41

我正在尝试编写一个插件,将扩展jQuery中现有的函数,例如:

(function($)
{
    $.fn.css = function()
    {
        // stuff I will be extending
        // that doesn't affect/change
        // the way .css() works
    };
})(jQuery);

我只需要扩展.css()函数的一些位。请原谅我的问题,我在考虑PHP类,因为您可以className extend existingClass,所以我想知道是否可以扩展jQuery函数。


2
你将会添加什么? - Daniel A. White
2个回答

82
当然可以…只需要保存一个对现有函数的引用,并调用它即可:
(function($)
{
    // maintain a reference to the existing function
    var oldcss = $.fn.css;
    // ...before overwriting the jQuery extension point
    $.fn.css = function()
    {
        // original behavior - use function.apply to preserve context
        var ret = oldcss.apply(this, arguments);

        // stuff I will be extending
        // that doesn't affect/change
        // the way .css() works

        // preserve return value (probably the jQuery object...)
        return ret;
    };
})(jQuery);

0

与该问题最佳答案略有不同,但方式相同:

// Maintain a reference to the existing function
const oldShow = jQuery.fn.show

jQuery.fn.show = function() {
  // Original behavior - use function.apply to preserve context
  const ret = oldShow.apply(this, arguments)

  // Your source code
  this.removeClass('hidden')

  return ret
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接