碰到有个继承了母版页的页面要加载body的onload事件,我发了一下午来解决这个问题,终于在国外某论坛上找到了解决方案
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>
国内的两种实现方法
1.客户端:
<script language="javascript" type="text/javascript">
window.onload=function getTime()
{
var date = new Date(); //日期对象
var now = "";
now = date.getFullYear()+"-"; //读英文就行了
now = now + (date.getMonth()+1)+"-"; //取月的时候取的是当前月-1如果想取当前月+1就可以了
now = now + date.getDate();
document.getElementById("txtAddDate").value=now;
}
</script>
2.服务器端:
protected override void Render(HtmlTextWriter writer)
{
//继承模板页的内容页加入 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('欢迎光临!');"));
}