用命名函数替换匿名函数(在jQuery中) [英] Replacing anonymous functions with named function (in jQuery)

查看:94
本文介绍了用命名函数替换匿名函数(在jQuery中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的原始(工作)代码如下所示:

My original (working) code looks like:

jQuery().ready(function ($) {
    $('[id="errorMessages"]').ajaxStart(function () {
        $(this).html("");
    });
    $('[id="errorMessages"]').ajaxError(function (e, jqxhr, settings, exception) {
        //...
    });
});

当我试图将匿名函数替换为命名函数时,调用如下:(我正在做某些要求的POC,期望这样的实现。)

When I am trying to replace the anonymous functions into a named function calls like: (I am doing a POC for some requirement, which expects such implementation.)

function fs() {
        $(this).html("");
}
function fe(e, jqxhr, settings, exception) {
        //...
}
jQuery().ready(function ($) {
    $('[id="errorMessages"]').ajaxStart(fs());
    $('[id="errorMessages"]').ajaxError(fe(e, jqxhr, settings, exception));
});

我收到错误,说明参数'e'未定义。但没有参数的函数似乎工作正常。

I am getting an error stating the parameter 'e' is undefined. But the functions without parameters seems working fine.

我想知道匿名函数如何接收参数,而调用外部函数时则不可用。

I am wondering how the anonymous functions could receive the parameters, while the same not available when calling an external function.

有没有办法将这些参数化的匿名函数转换为常规函数调用。

Is there a way to convert these parameterized anonymous functions into regular function calls.

推荐答案

您正在将函数分配给处理程序错误,请尝试以下操作:

You are assigning the functions to the handlers incorrectly, try this:

jQuery().ready(function ($) {
    $('[id="errorMessages"]').ajaxStart(fs);
    $('[id="errorMessages"]').ajaxError(fe);
});

请注意,传递没有括号的函数名称意味着您要提供该函数的引用当事件发生时使用。

Note that passing the name of the function without brackets means you are giving the reference of that function which should be used when the event occurs.

你的当前代码将在事件附加时调用该函数(因此你得到'e'的原因未定义)并将函数的结果赋给事件处理程序。

Your current code will call the function when the event is attached (hence why you're getting 'e' is undefined) and assign the result of the function to the event handler.

这篇关于用命名函数替换匿名函数(在jQuery中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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