是否有+ = JavaScript中的window.onload? [英] Is there += for window.onload in Javascript?

查看:151
本文介绍了是否有+ = JavaScript中的window.onload?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我想出了以下问题:

recently I came up with the following problem:

在所有的HTML页面调用我身体的onLoad事件的函数我的网站:

In my web site in all html pages I call a function in body onLoad event:

<body onLoad="func1();">

这是我对HTML模板的一部分,所以它出现在我的网站的每一页上,我无法改变这一点。现在,这笔交易是在一些网页上,我需要的onload调用一些其他的功能,我试图在window.onload属性,但它抹的func1的调用...

This is part of my template for html, so it appears on every page in my site and I can't change that. Now, the deal is that on some pages, I need to call some other functions onload and I tried with window.onload property, but it wipes the calling of func1...

我现在,我只能说:

window.onload = func2(); //where func2() calls to func1()

但这似乎肮脏,跛?难道不是吗?

but this seems dirty and lame? Isn't it ?

那么,有没有一种方法来添加一些功能,那些即将被执行的onload,而不删除旧的?另外我用asp.net是否可以帮助...

So, is there a way to add some functions to those that are about to be executed onload, without deleting the old one? In addition I use asp.net if that could help ...

谢谢!

推荐答案

您可以使用jQuery负载处理程序链。重复使用 jQuery.load 的jQuery(文件)。就绪将链中的处理程序(我相信)。你另一种选择是编程方式做到这一点,这意味着你需要将链中的onload事件处理你的一个辅助功能。

You can use jQuery to chain on load handlers. Repeatedly using jQuery.load or jQuery(document).ready will chain your handlers (I believe). You other option is to do it programmatically, which means you need an auxiliary function that will chain your onload handlers for you. You can do this with a closure (or anonymous function):

var addOnLoadHandler = function(newHandler) {

    if (typeof window.onload != 'function') {
        window.onload = newHandler;
    }

    else {
        var oldHandler = window.onload;
        window.onload = function() {
            if (oldHandler) {
                oldHandler();
            }
            newHandler();
        };
    }
};

您必须绑定你的编程功能,因此你必须做的:

You will have to bind your functions programmatically though, so you would have to do:

addOnLoadHandlers(function() {
 alert("Hi I am the first onLoad handler!");
});

addOnLoadHandlers(function() {
 alert("Hi I am the second onLoad handler!");
});

在JavaScript文件(或HTML文件)。

in a javascript file (or in your html file).

另一种方法是使用阵列

var onloaders = new Array();

function runOnLoads() {
    for (i = 0; i < onloaders.length; i++) {
        try {
            var handler = onloaders[i];
            handler();
        } catch(error) {
            alert(error.message);
        }
    }
}

function addLoader(obj) {
    onloaders[onloaders.length] = obj;
}

在你的HTML或JavaScript文件你这样做:

In your HTML or Javascript file you do:

addLoader(function() {
 alert("Hi I am the first onLoad handler!");
});

addLoader(function() {
 alert("Hi I am the second onLoad handler!");
});

然后在你的HTML你可以做&LT;身体的onload =runOnLoads()&GT;

这篇关于是否有+ = JavaScript中的window.onload?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆