代码之家  ›  专栏  ›  技术社区  ›  thecoshman

javascript回调函数中的“this”稍有混淆

  •  1
  • thecoshman  · 技术社区  · 15 年前
    $.ajax({url: path_to_file, cache: false, success: function(html_result){
        $("#window_" + this.id + "_cont_buffer").html(html_result);})
    

    现在。此函数调用包含在类的函数中。 this.id 是该类的属性。这会将this.id的函数值传递到匿名函数的字符串中,还是在实际调用函数时尝试对其进行计算,从而没有意义。

    如果我不想这样做,你能推荐我如何做到这一点吗?

    2 回复  |  直到 15 年前
        1
  •  2
  •   justkt    15 年前

    在特定情况下 $.ajax() , this 可以使用指定 context 属性。所以,马修的解决方案给了你 在您创建的函数中指定的 $.ajax 函数调用自。

    你可以看到 jQuery documentation 有关设置 对于 success 回拨。

        2
  •  1
  •   Matthew Flaschen    15 年前

    默认 this 将是内部jquery对象。但是,可以通过显式指定 context: this 作为电话的一部分。然后, 将是您调用它的对象。

    $.ajax({url: path_to_file, context: this, cache: false, success: function(html_result){
        $("#window_" + this.id + "_cont_buffer").html(html_result);})
    

    会做你想做的。