分享

asp.net中模板页(母版页)中调用body的onload事件的方法

 glxym 2015-05-09
国外网站的方法


碰到有个继承了母版页的页面要加载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('欢迎光临!');"));
     }





    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多