在JavaScript回调函数中轻微混淆`this`

时间:2010-04-29 13:48:49

标签: javascript jquery callback this anonymous-function

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

现在。此函数调用具有类的功能。 this.id是所述班级的财产。这会将this.id的函数值传递给匿名函数的字符串,还是会在函数实际被调用时尝试对其进行求值,因此没有任何意义。

如果这不符合我的要求,你能否推荐我如何实现这一目标。

2 个答案:

答案 0 :(得分:2)

$.ajax()的特定情况下,可以使用this属性指定context。因此,Matthew的解决方案为您提供了this函数中指定的$.ajax

有关为this回调设置success的详细信息,您可以看到jQuery documentation

答案 1 :(得分:1)

默认情况下,this将是一个内部jQuery对象。但是,您可以通过明确指定context: this作为调用的一部分来覆盖它。然后,this将成为您调用它的对象。

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

会做你想做的事。

相关问题