2013-09-30 100 views
0

在這個例子中,我試圖遍歷傳遞給點擊處理程序的對象的屬性,但我得到了意想不到的結果。 Here's小提琴將對象傳遞給事件jQuery

所以用JS腳本像

$(document).ready(function() 
     { 

      Label = function (name, toDate, fromDate) 
      { 
       this.name = name; 
       this.toDate = toDate; 
       this.fromDate = fromDate; 
      } 

      lbl = new Label('John', 'Today', 'Yesterday'); 


      $('#btnSubmit').click(function() 
      { 
       for (var i in lbl) 
       { 
        console.log(i); 
       } 
      }); 
      $('#btnSubmit2').click(function (Label) 
      { 
       for (var i in Label) 
       { 
        console.log(i); 
       } 
      }); 
     }); 

我爲什麼不能傳遞一個對象在點擊事件的功能和遍歷其屬性,而不是使用forin循環像我一樣的在btnSubmit的例子?

+0

你的編號問題是很難理解的,即使你的全球性問題似乎很清楚。 –

+0

你將如何獲得'btnSubmit2'處理程序中的標籤?因爲你命名變量'Label'?它只是參數名稱... – NDM

+0

@dystroy編輯爲什麼是最緊迫的我。 – wootscootinboogie

回答

2

回調總是以事件作爲參數調用。當你寫click(function(Label){時,你只給這個事件變量名稱Label(因此影射你的外部構造函數)。

但你可以訪問外部範圍定義的變量,所以你想要的東西可能是

var lbl = new Label('John', 'Today', 'Yesterday'); 
$('#btnSubmit').click(function(){ 
    for (var i in lbl) { 
     console.log(i, lbl[i]); // for example "name", "John" 
    } 
}); 
+0

這在我的第二個小提琴例子中是有道理的,因爲我有很多屬性我不熟悉,我認爲是事件對象的屬性。 – wootscootinboogie

+0

@wootscootinboogie準確無誤。 –

+0

這是有幫助的。我的思路是什麼我可以傳遞被點擊的對象的類型,並且有一個工廠方法被調用來創建該類型的對象(類似於..每個屬性的span標記,並將其綁定到頁面) 。很高興知道我正在走錯錯誤的兔子洞:) – wootscootinboogie