2016-11-23 212 views
0

我遇到問題。這是我第一次嘗試在Javascript中使用對象,並且遇到問題。Javascript:通過對象函數內的點擊函數調用對象函數

我有一個對象,其中包含一個DOM元素,我想添加到該元素的子元素點擊功能。在點擊函數內部,我想調用另一個對象函數,但這不起作用。要調用另一個對象函數,我必須使用this.functionname(),但因爲我在點擊函數this中不再是我的對象,而是添加了點擊函數的子元素。所以我的問題是:如何從點擊函數內部調用我的對象函數。

這是我的代碼(在代碼中的中間的,如果條件是不重要的):

function ManagementCard(card) { 
    this.card = card; 
    this.row = null; 
    this.rowAlt = null; 
    this.managementCard = this; 
} 

ManagementCard.prototype.initializeCard = function() { 

    this.card.find(".card ul li div:first-child").click(function() { 
     row = $(this).parent(); 

     if(this.rowAlt != null && this.rowAlt[0] != $(this).parent()[0]) 
     { 
      this.rowAlt.children("div:last-child").collapse('hide'); 
      $(this.rowAlt).css('background-color', ''); 
      $(this.rowAlt).css('color', ''); 
      this.rowAlt = null; 
     } 
     this.toggleManagementRow(); <=== Important! Call object-function from inside of a click-function which is inside the object-function 
    }); 
} 

ManagementCard.prototype.getCard = function() { 
    return this.card; 
} 

回答

2

保持參考物體在另一個變量例如self。它是這樣做在JavaScript

ManagementCard.prototype.initializeCard = function() { 
    var self = this; 
    this.card.find(".card ul li div:first-child").click(function() { 
     row = $(this).parent(); 

     if(this.rowAlt != null && this.rowAlt[0] != $(this).parent()[0]) 
     { 
      this.rowAlt.children("div:last-child").collapse('hide'); 
      $(this.rowAlt).css('background-color', ''); 
      $(this.rowAlt).css('color', ''); 
      this.rowAlt = null; 
     } 
     self.toggleManagementRow(); 
    }); 
} 
+0

非常感謝你:)簡單的解決方案 – kruben

+0

不只是接受的解決方案,請閱讀並試圖理解爲什麼它的工作原理 – mic4ael

+0

不用擔心常見的事,我明白爲什麼:) 再次感謝 – kruben