JavaScript jquery-ajax 里的 $(this) 怎么了?

dddd1919 · August 19, 2013 · Last by liaosong1015 replied at August 20, 2013 · 6287 hits

用 jquery 写了一个控件的 ajax 请求,发现 post 方法里的$(this) 出问题了,原文

$(".btn-onoff").click(function(){
        $.post("test", { onoff: $(this).html(), id: $(this).parent('div').attr("id")}, function(data,status){
          $(this).html(data);
        });
      });

结果没返回任何内容,用 alert 看了下结果是 undefined,在 stackoverflow 上查了一下,然后改用建议的方式:

$(".btn-onoff").click(function(){
        var $this = $(this);  //TODO why this
        $.post("test", { onoff: $this.html(), id: $this.parent('div').attr("id")}, function(data,status){
          $this.html(data);
        });
      });

结果正确了,想问下为什么 jq 里的 post 中直接写$(this) 无效呢?

js 是函数作用域,$.post 作用域就变了

callback 默认的 context 是 ajax 的 options 对象。JavaScript 中 this 是调用时绑 定的,还不是定义时绑定。一般把调用时绑定 this object 称为 context。问这样的问题 说明 JavaScript 还没入门,搜索多了解下 JavaScript 中的 this。

jQuery 是支持通过 option context 来设置 callbacks 绑定的 this object,不过 jQuery.post 是不支持 options,可以直接用 jQuery.ajax

另外碰到这种问题你把变量用 console.log 打出来不就清楚了吗?

$(".btn-onoff").click(function(){
  $.post(
    "test",
    {
      onoff: $(this).html(),
      id: $(this).parent('div').attr("id")
    },
    function(data, status) {
      console.log this; // => Object: {url: 'onoff=xx&id=xx', type: 'GET', ...}
    }
  );

  $.ajax({
    url: 'test',
    type:'POST',
    context: this,
    data: {
      onoff: $(this).html(),
      id: $(this).parent('div').attr("id")
    },
    success: function(data, statuts) {
      console.log this; // => [<button class="btn-onoff">...</button>]
    }
  );
});

@jyz19880823 @doitian 知道鸟,作用域的问题谢谢!确实还是没入门,一直用 alert 看信息,这回要学点高端大气上档次的了 :trollface:

#3 楼 @dddd1919 看看那本 javascript 语言精粹 ,很好的书

#4 楼 @jyz19880823 恩,感觉前端知识匮乏,要补补

在 firebug 下面加断点可以看到 this 绑定到那个了。

You need to Sign in before reply, if you don't have an account, please Sign up first.