传递包含参数的回调函数? [英] Passing a callback function with included parameters?

查看:33
本文介绍了传递包含参数的回调函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码..

function getGrades(grading_company) {

    if (grading_company == 'Not Specified') {

        // Remove grades box & show condition box
        showConditionBox();

    } else {

        // Set file to get results from..
        var loadUrl = "ajax_files/get_grades.php";

        // Set data string
        var dataString = 'gc_id=' + grading_company;

        // Set the callback function to run on success
        var callback = showGradesBox;

        // Run the AJAX request
        runAjax(loadUrl, dataString, callback);  

    }

}

function runAjax(loadUrl, dataString, callback) {

    jQuery.ajax({
        type: 'GET',
        url: loadUrl,
        data: dataString,
        dataType: 'html',
        error: ajaxError,
        success: function(response) {
            callback(response);
        }
    });    

}

这里是作为回调函数调用的函数:

Here is the function that gets called as the callback function:

function showGradesBox(response) {

    // Load data into grade field
    jQuery('#grade').html(response);

    // Hide condition fields
    jQuery('#condition').hide();
    jQuery('#condition_text').hide();

    // Show grade fields
    jQuery('#grade_wrapper').show();
    jQuery('#grade_text_wrapper').show();    

}

现在,如果我想将 grading_company 变量作为参数传递给回调函数,有没有一种方法可以做到这一点,而无需在 runAjax 打电话?我试图保持 runAjax 函数对其他用途开放,所以我不想传递任何额外的参数;但如果它可以以某种方式包含在回调中,那就太好了.

Now if I wanted to pass the grading_company variable to the callback function as a parameter is there a way to do that without having to add it as another parameter in the runAjax call? I'm trying to keep the runAjax function open to other usage so I don't want to pass in any extra parameters; but if it can somehow be included within the callback then great.

推荐答案

将回调更改为匿名函数:

change your callback to an anonymous function:

// Set the callback function to run on success
var callback = function () {
    showGradesBox(grading_company);
};

这允许您将参数传递给内部函数.

This allows you to pass parameters to the inner function.

允许ajax响应:

// Set the callback function to run on success
var callback = function (response) {
    showGradesBox(grading_company, response);
};

这篇关于传递包含参数的回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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