开发者

How do i write this piece of code in jquery?

开发者 https://www.devze.com 2023-02-04 13:35 出处:网络
How开发者_如何学Go do i write this piece of javascript code in Jquery <script> function init() {

How开发者_如何学Go do i write this piece of javascript code in Jquery

<script>
function init() {                

    alert('hi: ');
}

var previousOnload = window.onload;        
window.onload = function() { 
    if (previousOnload) { 
        previousOnload();
    }

    init();
}
</script>


Using jQuery, you don't have to "remember" the previous onload, both the window onload and the jQuery onload will run:

<script type="text/javascript">
    window.onload = function() {
        WriteLine("window onload");
    };

    $(function() {
        WriteLine("jQuery onload");
    });

    function WriteLine(msg) {
        alert(msg);
    }
</script>

Live test case: http://jsfiddle.net/SXQmT/


I would do the following:

function LoadEvent(Func)
{
    var OldOnLoad = window.onload;
    if (typeof OldOnLoad != 'function')
    {
        window.onload = Func;
    }else{
        window.onload = function()
        {
            OldOnLoad();
            Func();
        }
    }
}

And then use like so:

LoadEvent(Init);


$(window).load(init) would do almost the same thing. but without having previousOnload cluttering things up. It'll remember the previous onload for you, and call both when the page is fully loaded.

0

精彩评论

暂无评论...
验证码 换一张
取 消