将参数传递给事件处理程序

时间:2012-07-15 21:55:15

标签: javascript jquery

在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

},

5 个答案:

答案 0 :(得分:3)

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

var that = this;

$.ajax({
    ...
    success: function() {
        that.successFunction(msg);
    }
    ...
});

答案 1 :(得分: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
},

答案 2 :(得分: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虽然部分申请仍然没有记录,但是implemented

答案 3 :(得分:-1)

您可以使用闭包:

mySaveFunction: function(i) {
var msg = "my message " + i;
$.ajax({
  ...
  success: function(response) {
       alert(msg);  /* msg is available here */
  }
  ...
});

答案 4 :(得分:-1)

使用匿名函数:

  success: function() {
    this.successFunction(parameters);
  }