扩展现有的 jQuery 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5007279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extending an existing jQuery function
提问by MacMac
I am trying to write a plugin that will extend an existing function in jQuery, e.g.
我正在尝试编写一个插件来扩展 jQuery 中的现有功能,例如
(function($)
{
$.fn.css = function()
{
// stuff I will be extending
// that doesn't affect/change
// the way .css() works
};
})(jQuery);
There are only a few bits I need to extend of the .css()
function. Mind me for asking, I was thinking about PHP classes since you can className extend existingClass
, so I'm asking if it's possible to extend jQuery functions.
我只需要扩展该.css()
功能的几位。请注意我的提问,因为你可以className extend existingClass
,所以我在考虑 PHP 类,所以我问是否可以扩展 jQuery 函数。
回答by Test Employee 1
Sure... Just save a reference to the existing function, and call it:
当然...只需保存对现有函数的引用,然后调用它:
(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);
回答by Kevin Campion
Same way but a little different than the best answer of this question:
与此问题的最佳答案相同,但略有不同:
// 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
}