2016-11-22 62 views
0

如何在JavaScript中的另一個原型函數onclick事件內調用原型函數?如何在原型函數onclick事件中調用原型函數

function foo(){ 
    this.table = ''; 
} 

foo.prototype.abc = function(){ 
    this.table = document.getElementById("tableID"); 
    if (table != null) { 
     for (var i = 0; i < table.rows.length; i++) { 
      for (var j = 0; j < table.rows[i].cells.length; j++) 
      table.rows[i].cells[j].onclick = function() { 
       this.xyz(this); 
      }; 
     } 
    } 
} 

foo.prototype.xyz = function(tableCell){ 
    alert(tableCell.innerHTML); 
} 

如果我只是把這個tableText函數而不是this.xyz它會正常工作,但使用this.xyz在控制檯this.xyz(this)給出錯誤不是一個函數

function tableText(tableCell) { 
    alert(tableCell.innerHTML); 
} 

我的瀏覽器顯示錯誤,但不是的jsfiddle JS Fiddle

回答

0

在此代碼塊中:

table.rows[i].cells[j].onclick = function() { 
    this.xyz(this); 
}; 

this代表tdHTML對象,而不是foo。您必須保留foo的參考,並將其傳遞到onclick函數,如下所示:

foo.prototype.abc = function(){ 
    var that = this; //Keep a reference of `foo` 
    this.table = document.getElementById("tableID"); 
    if (table != null) { 
     for (var i = 0; i < table.rows.length; i++) { 
      for (var j = 0; j < table.rows[i].cells.length; j++) 
      table.rows[i].cells[j].onclick = function() { 
       //this.xyz(this); 
       // "that" refer to the function foo 
       // "this" refer to the current table cell (td) 
       that.xyz(this); 
      }; 
     } 
    } 
}