记录jQuery中调用的方法和参数 [英] Record methods and parameters called in jQuery

查看:88
本文介绍了记录jQuery中调用的方法和参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经加载了几个插件的jQuery。

Assume I have jQuery with several plugins loaded.

我运行了这样的代码:

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

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

I'd like to write a hook to jQuery in order to record a structure in which I will hold:


  • 使用了什么选择器

  • 调用了哪种方法

  • 它获得了什么参数

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

I know I can override both $() to catch selectors and I can add methods to jQuery (by writing plugins), but I'm not entirely sure how to get method's name and parameters while avoiding breaking the existing functionality of jQuery and its plugins.

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

Performance is not very important for this one, so any dynamic way to do it is also fine.

推荐答案

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

You could iterate over all the functions in $.fn and replace each one of them with your own function.

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

That function, in turn, can log the selector of the jQuery object it's called on and the arguments it received, then call the original function.

类似于:

$.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);
        };
    }
});

这篇关于记录jQuery中调用的方法和参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆