2015-08-27 65 views
-2

我正在使用Visual Studio 2010來覆蓋JS警告框,自定義模式box.I've使用下列內容:Overrinding JavaScript警告功能 - 不工作的動態添加JS

(function() { 
    var proxied = window.alert; 
    window.alert = function(txt) { 
    //myFuntion(txt); 
    return proxied.apply(this, arguments); 
    }; 
})(); 

這個js功能導致我的自定義彈出&警報框被顯示。來源taken from here

window.alert = function(txt) { 
    //myFuntion(txt); 
    }; 

作品只是罰款aspx頁面的腳本。 問題是通過使用RegisterStartupScript後面的代碼動態添加Js警報,並且RegisterClientScriptBlock仍顯示本地警報框。如何解決此問題。

+0

你爲什麼使用代理方法?這將調用你的函數,然後調用window.alert。該方法不會替代它剛添加到它的警報功能。 –

+0

我後來意識到自己的錯誤,但不知道如何解決這個問題。 – Chitransh

回答

0

您提供的第一個代碼示例中的代理方法旨在爲事件添加功能,而不是替換它。會發生什麼情況是當alert函數被調用時,它會調用你的函數,然後調用標準的window.alert函數。 (Codepen demonstration

(function() { 
    var proxied = window.alert; // stores the original window.alert function 
    window.alert = function(txt) { // sets a new window.alert 
    myfunction(); // calls your function 
    return proxied.apply(this, arguments); // calls the original window.alert function 
}; 
})(); 

第二種方法適合你,因爲它不使用代理服務器,它完全取代window.alert功能(Codepen demonstration

window.alert = function(txt) { // sets a new window.alert function 
    myfunction(); // calls your function 
}; 

的問題是最有可能的RegisterStartupScript和RegisterClientScriptBlock在您的腳本更新警報函數運行之前呈現它們的腳本。

+0

在contentplaceholder上方的母版頁中添加'myFuntion(txt);'即使在動態添加時也可以正確顯示修改後的警報 – Chitransh