我創建了一個庫,可以很容易地包含在我的所有網站中,以便輕鬆訪問此功能。
將這個類放入一個新的C#類庫項目中,以便您可以從其他項目(網站)中引用它。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyNameSpace.ConfirmLeavePageScript
{
[DefaultProperty("TextToDisplay")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]
public class ConfirmLeavePageScript : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("Are you sure you want to leave this page?")]
[Localizable(true)]
public string TextToDisplay
{
get
{
String s = (String)ViewState["TextToDisplay"];
return ((s == null) ? "Are you sure you want to leave this page?" : s);
}
set
{
ViewState["TextToDisplay"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
string script = @"
<script type='text/javascript'>
var confirmOnPageExit = function (e)
{
// If we haven't been passed the event get the window.event
e = e || window.event;
var message = '" + TextToDisplay + @"';
if(typeof ConfirmLeavePageMessage != 'undefined') //give client side the opportunity to overwrite the message instead of using message from ViewState.
{
message=ConfirmLeavePageMessage;
}
// For IE6-8 and Firefox prior to version 4
if (e)
{
e.returnValue = message;
}
// For Chrome, Safari, IE8+ and Opera 12+
return message;
};
function EnableConfirmOnPageExit()
{
// Turn it on - assign the function that returns the string
window.onbeforeunload = confirmOnPageExit;
}
function DisableConfirmOnPageExit()
{
// Turn it off - remove the function entirely
window.onbeforeunload = null;
}
</script>
";
output.Write(script);
}
}
}
您可以在您的web站點項目中註冊標記前綴,方法是將其放置在web.config中。確保你的網站添加了C#類庫項目作爲參考(把它們放在同一個解決方案中)。
<configuration>
<system.web>
<pages>
<controls>
<add tagPrefix="tna" assembly="ConfirmLeavePage" namespace="MyNameSpace.ConfirmLeavePageScript" />
</controls>
</pages>
</system.web>
</configuration>
然後,將控件放在內容頁面的頭部。
<head>
<tna:ConfirmLeavePageScript runat="server" TextToDisplay="Are you sure you want to leave without saving?" />
</head>
在這種檢測是否已經作了修改,調用這個函數JavaScript函數:
EnableConfirmOnPageExit();
你也可以做以下(我認爲是自我解釋):
<script type="text/javascript>
ConfirmLeavePageMessage="new message"; //set a custom message from JavaScript for the confirmation window
DisableConfirmOnPageExit(); //Disables the confirmation window (user can leave page without seeing the confirmation window)
</script>
我不知道你的問題是什麼... – epascarello
我希望在確認時點擊「確定」,禁用離開頁面而不保存 – mich
這是不可能的 – epascarello