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

查看:34
本文介绍了用命名函数替换匿名函数(在 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天全站免登陆