记录jQuery中调用的方法和参数

假设我有几个插件加载的jQuery。

我运行这样的代码:

$('someSelector').someMethod('someParam', 'someOtherParam'); $('someOtherSelector').someOtherMethod('anotherParam'); $('anotherSelector').anotherMethodWhichMayOrMayNotBeAPlugin(); 

我想写一个jQuery的钩子来记录我将持有的结构:

  • 使用了什么选择器
  • 调用了哪种方法
  • 它得到了什么论据

我知道我可以覆盖$()以捕获选择器,我可以添加方法到jQuery(通过编写插件),但我不完全确定如何获取方法的名称和参数,同时避免破坏jQuery及其插件的现有function。

性能对于这个并不是很重要,所以任何动态的方法都可以。

您可以迭代$.fn所有函数,并用您自己的函数替换它们中的每一个。

反过来,该函数可以记录它所调用的jQuery对象的选择器和它接收的参数,然后调用原始函数。

就像是:

 $.each($.fn, function(key, func) { if ($.isFunction(func)) { $.fn[key] = function() { console.log("Method '" + key + "' was called"); console.log(" on selector '" + this.selector + "'"); console.log(" with arguments: " + arguments); return func.apply(this, arguments); }; } });