【问题标题】:call dynamic jquery function in objects在对象中调用动态jquery函数
【发布时间】:2012-09-02 11:41:59
【问题描述】:

你好,我找到了一篇关于stackoverflow如何调用动态函数的文章:

function mainfunc(func) {
    this[func].apply(this, Array.prototype.slice.call(arguments, 1));
}

这非常有用。但是我怎样才能在我的对象函数中调用函数呢?

我得到一个错误:

"TypeError: this[func] 未定义 this[func].apply(this, Array.prototype.slice.call(arguments, 1));"

看起来像:

var myScript = {
...
add : function() {
...
myScript.ajax('url.php', params, 'myScript.add2List');
},

add2List : function(data) {
console.log(data);
},

ajax : function(url, params, func) {
  $.ajax({
      type: "POST",
      url: url,
      data: params,
      success: function(data) {
        console.log(func);
        mainfunc(func, data);
      }
  });
 }
}

【问题讨论】:

    标签: jquery object dynamic call


    【解决方案1】:

    您不需要使用该功能,您可以执行以下操作。

    var myScript = {
    ...
    add : function() {
      ...
      myScript.ajax('url.php', params,  this.add2List);
    },
    
    add2List : function(data) {
      console.log(data);
    },
    
    ajax : function(url, params, func) {
      $.ajax({
          type: "POST",
          url: url,
          data: params,
          success: func
      });
     }
    }
    

    【讨论】:

    • 嗨 xdazz。非常感谢它以这种方式工作。但它不适用于“this”,我必须改写“myScript”。它找不到这个 - 不知道 ;)
    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 2015-04-04
    • 2011-10-26
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多