2012-08-15 29 views
-1

當我想在嵌套語句中引用「this」時會發生什麼?

下面是一個例子來說明我通過上面的意思是:

$("input").blur(function(){ 
      var theThis = $(this); 
      if(!($(".invalid").length > 0)){ 
       //if there's no messages already open 
       theThis.data("validator").checkValidity(); 
      }else{ 
       //add the message to the next to be displayed 
       nextToAlert.push(theThis); 
       //bind an event to the errored field being changed 
       $(".invalid").on("change", function(){ 
        var me = $(this); 
        if(!me.hasClass('invalid')){ 
         nextToAlert.pop().checkValidity(); 

        } 
       }); 
      } 
    }); 
+0

元素被選中,這就是發生了什麼 – 2012-08-15 08:54:15

+0

是的,不是一個很好的問題。 – Archer 2012-08-15 08:55:10

+0

所以第二個這是本地的,第一個這是超出範圍? – 2012-08-15 08:56:03

回答

1

在您的代碼:

  • theThis$("input")
  • me翻領到$(".invalid")

$(this)將始終視當前範圍改變。

當你使用任何類型的動作結合的功能,如bluronbindlive等,然後將$(this)引用當前jQuery對象,該事件被綁定到。

1

this article更好地瞭解$(this)。規則:$(this)作爲一個簡單的(並不總是正確的,但在99%的情況下)將引用當前執行上下文中的元素(DOM文檔中的當前位置)。

在您的例子:

  • theThis將(當前)$("input")
  • me將(當前)$(".invalid")
+2

如果多個'$(「。無效「)','$(this)'每次只引用其中的一個 – 2012-08-15 08:58:13

+0

因此(當前)'$(」無效「)'。同樣適用於'thisThis'。 – 2012-08-15 08:59:44

1

Javascript使用函數作用域:值this取決於如何調用包含它的最內層函數。當您撥打object.method()時,該方法內的值爲thisobject;如果您撥打function(),則this的值爲window。您也可以撥打function.call(thisValue)this設置爲任意值。當funcion是回調函數時,值this取決於完全取決於調用它的代碼,所以您的主要信息源應該是jQuery文檔。但通常jQuery會將this設置爲動作發生的DOM元素。例如。對於$('.foo').on('click', myFunc)this的值將在myFunc中被捕獲點擊的元素,因爲$('.foo').each(myFunc)它將成爲集合中的當前元素,依此類推。 $(this)然後用於將DOM元素轉換爲jQuery元素。