0

在 jquery 中,如何将附加参数传递给事件处理函数?

所以例如

mySaveFunction: function(i) {
var msg = "my message " + i;
$.ajax({
  ...
  success: this.successFunction, // i want to pass msg to successFunction
  ...
});

successFunction: function(response) {
   // do something with msg

},
4

5 回答 5

3

匿名函数应该在这里解决问题。但是,在匿名函数内部,this.successFunction将是未定义的,因此我们需要存储this对匿名函数外部的引用。

var that = this;

$.ajax({
    ...
    success: function() {
        that.successFunction(msg);
    }
    ...
});
于 2012-07-15T21:59:14.690 回答
0

您可以为此使用闭包:

mySaveFunction: function(i) {
    var self = this; // <=== Grab what `this` is
    var msg = "my message " + i;
    $.ajax({
      ...
      success: function(response) {
          self.successFunction(response, msg); // <=== Use it and `msg `here
      ...
    });
// ...

successFunction: function(response) {
   // do something with msg
},
于 2012-07-15T22:00:16.670 回答
0

您可以使用$.proxy

mySaveFunction: function(i) {
    var msg = "my message " + i;
    $.ajax({
          ...
        success: $.proxy(this.successFunction, this, msg), // i want to pass msg to 
          ...
    });
},
successFunction: function(msg, response) {
    // do something with msg
},

Docs虽然部分应用程序仍然没有记录但已实现

于 2012-07-15T22:10:34.910 回答
-1

使用匿名函数:

  success: function() {
    this.successFunction(parameters);
  }
于 2012-07-15T21:57:39.777 回答
-1

您可以使用闭包:

mySaveFunction: function(i) {
var msg = "my message " + i;
$.ajax({
  ...
  success: function(response) {
       alert(msg);  /* msg is available here */
  }
  ...
});
于 2012-07-15T21:56:54.450 回答