我寫它接受一個Button
對象,並應設置onclick
客戶端腳本,有條件調用現有客戶端腳本的功能。例如,如果我開始與一個按鈕,這會使像:如何包裝/窩的JavaScript調用使用「這個」?
<input type="button" value="ok" id="ok"
onclick="existingClickHandler(this);"
/>
我想以編程方式設置OnClientClick
這個按鈕,所以會呈現是這樣的:
<input type="button" value="ok" id="ok"
onclick="Wrapper(function { existingClickHandler(this); });"
/>
的問題是,現有的代碼使用this
,我不知道如何在這樣一種方式,this
仍然指向正確的對象寫Wrapper()
。
我怎樣才能讓existingClickHandler
繼續正常運行時Wrapper()
叫什麼名字?
更新:根據要求的情況是我寫的ASP.NET功能禁用點擊按鈕,以防止雙重職位,對於一些用戶界面的響應。在我的服務器端的C#代碼我有一個功能(這已經凝結位爲清楚起見):
void AutoDisableButtons(Button sourceButton, params Button[] buttonsToDisable)
{
string oldScript = sourceButton.OnClientClick;
if (string.IsNullOrEmpty(oldScript))
oldScript = "null";
else
oldScript = "function(){" + oldScript + ";}";
postbackEventScript = ....
buttonsToDisableArrayScript = ....
sourceButton.OnClientClick = "return DisableButtonsOnSubmit.call(this, " + oldScript + ", " + postbackEventScript + ", " + buttonsToDisableArrayScript + ");";
}
以及相應的客戶端腳本:
function DisableButtonsOnSubmit(oldClickScript, postbackEventReference, buttonsToDisableArray)
{
if((typeof(Page_ClientValidate) == 'function') && !Page_ClientValidate())
return false;
if((typeof(oldClickScript) == 'function') && !oldClickScript.call(this))
return false;
for (var i=0; i<buttonsToDisableArray.length; i++)
{
if(null != document.getElementById(buttonsToDisableArray[i]))
{
document.getElementById(buttonsToDisableArray[i]).disabled = true;
}
}
postbackEventReference.call(this);
return true;
}
注意,這個代碼包括.call()
解決方案提出@herostwist
如果您想了解'.call'的功能:http://odetocode.com/blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx – herostwist 2011-05-09 10:32:11
我不知道「電話」,但這正是我所尋找的。 – tenfour 2011-05-09 10:32:39
如果你將'this'作爲參數#1傳遞,並且不設置上下文,爲什麼不使用'onclick =「existingClickHandler(this)」'? 'this'將成爲參數#1,就像你的代碼一樣...... – Rudie 2011-05-09 10:35:26