2011-05-09 19 views
1

我寫它接受一個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

回答

1

的能力,我想你想要的是按鈕傳遞給existingClickHandler,仍然有this引用不同的對象中existingClickHandler

這種假設是真實試試這個:

<input type="button" value="ok" id="ok" 
    onclick="existingClickHandler.call(SomeObjectForThis, this);" 
/> 

哪裏SomeObjectForThis是你想要thisexistingClickHandler

+0

如果您想了解'.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

+0

我不知道「電話」,但這正是我所尋找的。 – tenfour 2011-05-09 10:32:39

+0

如果你將'this'作爲參數#1傳遞,並且不設置上下文,爲什麼不使用'onclick =「existingClickHandler(this)」'? 'this'將成爲參數#1,就像你的代碼一樣...... – Rudie 2011-05-09 10:35:26

0

您可以存儲「這個」在一個變量和使用變量而不是:

<input type="button" value="ok" id="ok" 
    onclick="var that=this; Wrapper(function { existingClickHandler(that); });" 
    /> 
1

如果不設置對象引用「這個」將指向全局的window對象。事情是由你失去了做到這一點的能力html標記使用輸入的onclick。

你想要什麼是很可能是這樣的(使用jquery)

$( '#ID')點擊(函數clickHandler事件(){// 代碼在這裏 })。

一旦你這樣做,你必須調用處理在正確的範圍

相關問題