2012-07-27 21 views
2

當我執行下面的代碼時,我期望相同的元素id被警告兩次,但是第一個是正確的,而第二個總是顯示名稱該集合中的第一個元素。

$("div.someClass").each(function (index) { 
    $(this).click(function() { 
    alert($(this).attr("id")); // Here i get the actually clicked element 
    $.when($("div.someClass").animate({ }, 0)).then(function() { 
     alert($(this).attr("id")); // Here i get the first element in of that class 
    }); 
    }); 
}); 

爲什麼會這樣?如何解決它?我試過將元素的名稱傳遞給函數,但它不起作用。

+0

當你點擊一個div時,你希望它們都具有相同類別的動畫?您正在重新選擇'$ .when'中的div,因爲只有在抓取集合中第一個項目的id屬性時才調用'.then'回調。 – MrOBrian 2012-07-27 17:00:31

回答

4

保存在例如that後來使用的一些變量$(this)animate

$("div.someClass").each(function (index) { 
    $(this).click(function() { 
    alert($(this).attr("id")); // Here i get the actually clicked element 
    var that = $(this); 
    $.when($("div.someClass").animate({ }, 0)).then(function() {   
     alert(that.attr("id")); // Here i get the first element in of that class 
     alert($(this).attr("id")); 
    }); 
    }); 
}); 
+1

編輯:你忘了'var'你''那個'變量。就像你那樣,這是一個全球性的,共享的。 'var'是一個局部變量,在'then'處理程序中關閉了 – Phrogz 2012-07-27 17:00:03

+0

謝謝Phrogz,你真好。 – Adil 2012-07-27 17:01:58

4

this值自動改變對每個函數調用。因此,除非多個函數調用通過傳遞它,然後使用.apply().call()在調用回調函數之前將其設置爲特意保留特定值this,否則它將有所不同。 Javascript遵循以下規則:

  • 如果您進行方法調用,則將值this設置爲其方法的對象。
  • 如果您進行正常的函數調用,則將this設置爲全局對象(通常爲window)。
  • 如果使用fn.apply()fn.call(),則根據第一個參數設置this

最簡單的解決方案是將this的值保存在局部變量中,然後引用它。

$("div.someClass").each(function (index) { 
    var self = $(this); 
    self.click(function() { 
    alert(self.attr("id")); // Here i get the actually clicked element 
    $.when($("div.someClass").animate({ }, 0)).then(function() { 
     alert(self.attr("id")); // Here i get the first element in of that class 
    }); 
    }); 
}); 
2

您需要訪問的每個功能的元素:http://api.jquery.com/each/

$("div.someClass").each(function (index, element) { 
    $(element).click(function() { 
    var $this = $(this); 
    alert($this.attr("id")); // Here i get the actually clicked element 
    $.when($("div.someClass").animate({ }, 0)).then(function() { 
     alert($this.attr("id")); // Here i get the first element in of that class 
    }); 
    }); 
}); 

也有助於什麼「這」指讀了起來:https://developer.mozilla.org/en/JavaScript/Reference/Operators/this jQuery的可以迷惑你的是什麼「這個」的理解應該是所有的上下文改變它爲事件處理。