碰到有個(gè)繼承了母版頁(yè)的頁(yè)面要加載body的onload事件,,我發(fā)了一下午來(lái)解決這個(gè)問(wèn)題,,終于在國(guó)外某論壇上找到了解決方案
Method1:
In the master page make the body a control by giving the runat="server" attribute and a name.
<body runat="server" id="MyBody">
Next, use the following code in the Page_Load event of the page (Default.aspx or any other page which inherits from the master page).
HtmlGenericControl body = (HtmlGenericControl)
Page.Master.FindControl("MyBody");
body.Attributes.Add("onload", "alert('hello world')");
And, thats it! Now the body event is only generated for a particular page.
Method2:
Hi. It's a good solution! But try also my approach
1. in MasterPage create ContentPlaceHolder for just opening <body> tag:
<asp:contentplaceholder id="BodyPlaceHolder1" runat="server"><body></asp:contentplaceholder>
2. in your .aspx pages create specific content with onload event
<asp:Content ontentPlaceHolderID=BodyPlaceHolder1 runat=server>
<body onload="alert('hello');">
</asp:Content>
國(guó)內(nèi)的兩種實(shí)現(xiàn)方法
1.客戶(hù)端:
<script language="javascript" type="text/javascript">
window.onload=function getTime()
{
var date = new Date(); //日期對(duì)象
var now = "";
now = date.getFullYear()+"-"; //讀英文就行了
now = now + (date.getMonth()+1)+"-"; //取月的時(shí)候取的是當(dāng)前月-1如果想取當(dāng)前月+1就可以了
now = now + date.getDate();
document.getElementById("txtAddDate").value=now;
}
</script>
2.服務(wù)器端:
protected override void Render(HtmlTextWriter writer)
{
//繼承模板頁(yè)的內(nèi)容頁(yè)加入 onload 事件
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
base.Render(htw);
writer.Write(sw.ToString().Replace("<body", "<body onload=javascript:alert('歡迎光臨!');"));
}