jQuery的更多参数传递到回调 [英] jQuery pass more parameters into callback

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

问题描述

有没有一种方法来传递更多的数据到jQuery中的回调函数?

Is there a way to pass more data into a callback function in jQuery?

我有两个功能,我想回调到 $。交,例如,通过在AJAX通话双方所得到的数据,以及一一些自定义的参数

I have two functions and I want the callback to the $.post, for example, to pass in both the resulting data of the AJAX call, as well as a few custom arguments

function clicked() {
    var myDiv = $("#my-div");
    // ERROR: Says data not defined
    $.post("someurl.php",someData,doSomething(data, myDiv),"json"); 
    // ERROR: Would pass in myDiv as curData (wrong)
    $.post("someurl.php",someData,doSomething(data, myDiv),"json"); 
}

function doSomething(curData, curDiv) {

}

我希望能够在自己的参数传递给回调,以及来自AJAX调用返回的结果。

I want to be able to pass in my own parameters to a callback, as well as the result returned from the AJAX call.

谢谢!

推荐答案

解决的办法是变量绑定到结束。

The solution is the binding of variables through closure.

我没有使用jQuery中。员额的功能,但文档的快速扫描显示回调应该是函数指针接受如下:

I haven't used the .post function in jQuery, but a quick scan of the documentation suggests the call back should be a function pointer accepting the following:

function callBack(data, textStatus, jqXHR) {};

因此​​,我认为解决方法如下:

Therefore I think the solution is as follows:

var doSomething = function(extraStuff) {
    return function(data, textStatus, jqXHR) {
        // do something with extraStuff
    };
};

var clicked = function() {
    var extraStuff = {
        myParam1: 'foo',
        myParam2: 'bar'
    }; // an object / whatever extra params you wish to pass.

    $.post("someurl.php", someData, doSomething(extraStuff), "json");
};

这是怎么回事?

What is happening?

在最后一行, DoSomething的(extraStuff)引用和该调用的结果是函数指针

In the last line, doSomething(extraStuff) is invoked and the result of that invocation is a function pointer.

由于 extraStuff 被作为参数传递给 DoSomething的是范围之内的 DoSomething的的功能。

Because extraStuff is passed as an argument to doSomething it is within scope of the doSomething function.

extraStuff DoSomething的返回的匿名内部函数引用它必然由封闭到外部函数的 extraStuff 参数。这甚至在是真实的DoSomething的又回来了。

When extraStuff is referenced in the returned anonymous inner function of doSomething it is bound by closure to the outer function's extraStuff argument. This is true even after doSomething has returned.

我没有测试以上,但我已经写的很类似code在过去的24小时,它可以作为我所描述的。

I haven't tested the above, but I've written very similar code in the last 24 hours and it works as I've described.

您当然可以通过,而不是一个单一的extraStuff对象,取决于你个人的preference /编码标准的多个变量。

You can of course pass multiple variables instead of a single 'extraStuff' object depending on your personal preference/coding standards.

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

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