2012-01-23 73 views
0

的函數如何將參數傳遞給聲明爲something = function(){}的函數?如何將參數傳遞給聲明如left = function()

window.prototype.initInterface = function(){ 
    this.mainPane = document.createElement('div'); 
    this.mainPane.style.border="5px solid grey"; 
    this.mainPane.style.margin="0px"; 
    this.mainPane.style.width="420px"; 
    this.mainPane.style.height="600px"; 

    this.exitButton = document.createElement('input'); 
    this.exitButton.setAttribute("type", "button"); 
    this.exitButton.setAttribute("value", "exit"); 

    this.exitButton.onclick = function(){ 
     document.body.removeChild(this.mainPane); 
    }; 

    this.mainPane.appendChild(this.exitButton); 

    document.body.appendChild(this.mainPane); 
} 

當用戶按下退出鍵我想從html頁面的清除體內的mainPane。

this.exitButton.onclick = function(this.mainPage){ 
     document.body.removeChild(this.mainPane); 
    }; 

不工作

我怎樣才能做到這一點?

+0

'window.prototype'?我不認爲'window'是一個構造函數... –

+0

[我如何在事件處理程序中訪問'this'](http://stackoverflow.com/questions/7696672/how-can-i -access-this-in-an-event-handler) –

+0

謝謝,下面的工作: var self = this; this.exitButton.onclick = function(){ \t document.body.removeChild(self.mainPane); }; –

回答

0

爲了您exitButton.onclick函數訪問的變量獲得該匿名函數的一些DOM參數,你在你想要的包絡initInterface函數來創建a在exitButton.onclick函數中創建一個閉包,方法是返回一個執行所需操作並將該變量傳遞給該函數的函數。

exitButton.onclick = function() { 
    return (function() { 
     document.body.removeChild(mainPane); 
    })(mainPane); 
}; 

瞭解更多關於如何關閉工作herehere,看到工作example fiddle

或者,你忘了關閉和從觸發事件您mainPane

exitButton.onclick = function() { 
    // in here "this" is the object that triggered the event, exitButton 
    document.body.removeChild(this.parentNode); 
} 

順便按鈕向上走的DOM,window.prototype不存在,如果你在瀏覽器中完成這個工作window是瀏覽器腳本中原型鏈頂部的對象。您只需要window.initInterface = function() {}這與function initInterface() {}完全相同,因爲您在瀏覽器中的所有JavaScript操作都會成爲window的屬性。

-1

該函數是沒有函數名稱的函數。它只能使用一次,你可能不容易找出應該傳遞什麼參數。

您可以創建像另一個功能:

功能去(A1){}

,並調用它像window.prototype.initInterface =去(A1);

或者,您可以通過使用功能,如getDocumentById(「DOM ID」)等

+0

這是不正確的。首先'函數去(var a1){}'是無效的JavaScript。其次,函數在調用時不需要名稱就可以傳遞參數:'var foo = function(bar){...}'。混淆更多的是*定義*函數和*調用*它。在OP的代碼中,他定義了一個函數,因此每個參數的名稱都必須遵循一定的規則,例如一個名稱不能包含「。」。 –

+0

感謝您的糾正!我的錯。我仍然建議使用一些可以重複使用的名稱的函數,並且更好地瞭解應該傳遞哪些參數。 – Wangsu

相關問題