2014-01-13 30 views
0

海蘭,調用函數中動態創建按鈕

我試圖執行一個功能,更精確清晰的畫布重繪,動態創建的按鈕中。 addButton函數在接口上現有按鈕的單擊事件中調用。代碼是這樣的:

function addButton() 
{ 
var canvas=document.getElementById('CrosswordSpace'); 
this.context=canvas.getContext("2d"); 
var parent = document.getElementsByName('gen')[0].parentNode; 
var element=document.createElement("input"); 
element.type='button'; 
element.name='buttonAnswer'; 
element.value='Show answer'; 
element.onclick=function() 
{ 
    this.context.clearRect(0,0,300,300); 
} 
parent.appendChild(element); 
this.onclick=null; 
} 

錯誤說'不能調用undefined的方法clearRect。 如果你問我爲什麼要使用this.onclick = null,那是因爲在使用這個語句之前,動態創建的按鈕會在每次按下主按鈕時自我複製,而我不想那樣做。 無論如何,如果我在onclick裏面調用動態創建的按鈕,其他任何在其他地方(測試)運行 的函數似乎都不再工作了。 總而言之,問題是,如何在動態創建的按鈕的onclick事件中調用一個函數? 謝謝。

回答

4

您需要在回調中使用的原始方法保留this值,因爲回調可以改變this

var self = this; 
element.onclick=function() 
{ 
    self.context.clearRect(0,0,300,300); 
} 
+0

意思不知道,非常感謝你! –