【问题标题】:Using $(this) inside a setInterval in jQuery在 jQuery 的 setInterval 中使用 $(this)
【发布时间】:2011-12-06 21:18:38
【问题描述】:

我在 jQuery 插件中使用此代码:

setInterval(function() {                        
   localStorage.setItem("flag", "set");
   var data = $(this).serializeArray();
   console.log($(this));
   $.each(data, function(i, obj) {
      localStorage.setItem(obj.name, obj.value);
   });
   console.log('saved');
   console.log(localStorage);                       
}, 5000);

if (localStorage.getItem("flag") == "set") {
   alert("This form has saved data!");
   var data = $(this).serializeArray();
   console.log($(this));
   $.each(data, function(i, obj) {
      $("[name='" + obj.name +"']").val(localStorage.getItem(obj.name));
   });                      
}

现在奇怪的是,第一个 $(this) 包含表单(运行插件),但第二个 $(this) 包含 DOMWindow。为什么这两个$(this) 包含不同的东西?是因为第一个在setInterval 内吗?

【问题讨论】:

  • 是的,还要注意this 在很多情况下会被 JQuery 覆盖。

标签: jquery this setinterval


【解决方案1】:

是的,您的 setInterval 声明中有一个匿名函数(没有名称的函数),它创建了自己的范围。

第一个 console.log($(this)) 将可以访问任何全局或任何在其内部设置的内容,第二个 console.log($(this)) 将只能访问全局变量(正如您所发现的,全局范围内的 thiswindow 对象)。

【讨论】:

    【解决方案2】:

    您可以使用简单的闭包,也可以使用$.proxy:http://api.jquery.com/jQuery.proxy/

    var repeat = function() {                        
        localStorage.setItem("flag", "set");
        var data = $(this).serializeArray();
        .......
    }
    
    setInterval($.proxy(repeat, $("#form")), 500);
    

    类似的...

    【讨论】:

      【解决方案3】:

      不是在setInterval 里面,而是在那个匿名函数里面。

      第一个$(this) 在匿名函数的范围内。第二个$(this) 在全局范围内。

      【讨论】:

        【解决方案4】:

        this 是对当前对象的引用。它表示函数的上下文。默认引用是全局引用(在我们的例子中是 window 对象)。
        因为setInterval 回调是在全局范围内执行的,所以this 将始终指向窗口对象。
        以下是一些说明this 与范围之间联系的示例:

        var a = "window";
        function f(){
            console.log(this.a);
        }
        f();// scope = window
        var obj = {a:'object',f:f};
        obj.f();// scope = object
        

        【讨论】:

          猜你喜欢
          • 2021-07-30
          • 2012-07-31
          • 2021-02-27
          • 2012-11-27
          • 2013-02-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多