2016-11-22 2 views
0

Wie kann ich die Prototyp-Funktion innerhalb einer anderen Prototyp-Funktion aufrufen onclick Ereignis in JavaScript?So rufen Sie die Prototyp-Funktion in der Prototyp-Funktion onclick-Ereignis auf

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); 
} 

Wenn ich diese statt this.xyztableText Funktion nur aufrufen wird es funktionieren, aber this.xyz gibt in der Konsole this.xyz(this) Fehler mit nicht eine Funktion

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

Fehler Mein Browser zeigt aber nicht JSFiddle JS Fiddle

Antwort

0

In diesem Codeblock:

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

this repräsentiert das td HTML-Objekt, nicht foo. Sie haben einen Verweis von foo zu halten und sie in onclick Funktion übergeben, wie folgt aus:

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); 
      }; 
     } 
    } 
} 
Verwandte Themen