Hook a javascript event to page load

2019-01-14 21:09发布

I have an aspx that has the following javascript function being ran during the onload event of the body.

<body onload="startClock();">

However, I'm setting the aspx up to use a master page, so the body tag doesn't exist in the aspx anymore. How do I go about registering the startClock function to run when the page is hit and still have it use a masterpage?

4条回答
聊天终结者
2楼-- · 2019-01-14 21:32

The cleanest way is using a javascript framework like jQuery. In jQuery you could define the on-load function in the following way:

$(function() {
    // ...
});

Or, if you don't like the short $(); style:

$(document).ready(function() {
    // ...
});
查看更多
等我变得足够好
3楼-- · 2019-01-14 21:44

Insert this anywhere in the body of the page:

<script type="text/javascript">
window.onload = function(){
    //do something here
}
</script>
查看更多
虎瘦雄心在
4楼-- · 2019-01-14 21:46
Page.ClientScriptManager.RegisterStartupScrip(this.GetType(), "startup", "startClock();", true);

or using prototype

document.observe("dom:loaded", function() {
  // code here
});
查看更多
劫难
5楼-- · 2019-01-14 21:54

If you don't want to explicitly assign window.onload or use a framework, consider:

<script type="text/javascript">
function startClock(){
    //do onload work
}
if(window.addEventListener) {
    window.addEventListener('load',startClock,false); //W3C
} else {
    window.attachEvent('onload',startClock); //IE
}
</script>

http://www.quirksmode.org/js/events_advanced.html

查看更多
登录 后发表回答