javascript 在 window.onload 中添加两个函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16683176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:37:43  来源:igfitidea点击:

Add two functions to window.onload

javascriptfunction

提问by AJJ

I have two functions on my form except one does not work if the other is active. Here is my code:

我的表单上有两个功能,但如果另一个功能处于活动状态,则其中一个功能不起作用。这是我的代码:

window.onload = function(event) {
    var $input2 = document.getElementById('dec');
    var $input1 = document.getElementById('parenta');
    $input1.addEventListener('keyup', function() {
        $input2.value = $input1.value;
    });
}

window.onload=function(){
    document.getElementById('enable').onchange=function(){
        var txt = document.getElementById('gov1');
        if(this.checked) txt.disabled=false;
        else txt.disabled = true;
    };
};

What I mean is that when I have both these functions in my form the second function works fine but the first will not work, if take out the second function the first one will work like normal, why is this happening? Is it because of the names?

我的意思是,当我的表单中有这两个函数时,第二个函数可以正常工作,但第一个函数不起作用,如果取出第二个函数,第一个函数会正常工作,为什么会发生这种情况?是因为名字吗?

采纳答案by Janak

Try putting all you code into the same [and only 1] onload method !

尝试将所有代码放入相同的 [并且只有 1] 个 onload 方法中!

 window.onload = function(){
        // All code comes here 
 }

回答by Khanh TO

window.addEventListener("load",function(event) {
    var $input2 = document.getElementById('dec');
    var $input1 = document.getElementById('parenta');
    $input1.addEventListener('keyup', function() {
        $input2.value = $input1.value;
    });
},false);

window.addEventListener("load",function(){
    document.getElementById('enable').onchange=function(){
        var txt = document.getElementById('gov1');
        if(this.checked) txt.disabled=false;
        else txt.disabled = true;
    };
},false);

Documentation is here

文档在这里

Note that this solution may not work across browsers. I think you need to rely on a 3-rd library, like jquery $(document).ready

请注意,此解决方案可能无法跨浏览器工作。我认为你需要依赖第三个库,比如 jquery$(document).ready

回答by chad

If you can't combine the functions for some reason, but you have control over one of them you can do something like:

如果由于某种原因您无法组合这些功能,但您可以控制其中一个功能,则可以执行以下操作:

window.onload = function () {
    // first code here...
};

var prev_handler = window.onload;
window.onload = function () {
    if (prev_handler) {
        prev_handler();
    }
    // second code here...
};

In this manner, both handlers get called.

以这种方式,两个处理程序都被调用。

回答by Leniel Maccaferri

You cannot assign two different functions to window.onload. The last one will always win. This explains why if you remove the last one, the first one starts to work as expected.

您不能将两个不同的功能分配给window.onload。最后一个永远是赢家。这解释了为什么如果您删除最后一个,第一个开始按预期工作。

Looks like you should just merge the second function's code into the first one.

看起来您应该将第二个函数的代码合并到第一个函数中。

回答by elclanrs

Because you're overriding it. If you want to do it with onloadyou could just extend the previous function. Here's one way to do it:

因为你要覆盖它。如果你想这样做,onload你可以扩展以前的功能。这是一种方法:

Function.prototype.extend = function(fn) {
  var self = this;
  return function() {
    self.apply(this, arguments);
    fn.apply(this, arguments);
  };
};

window.onload = function() {
  console.log('foo');
};

window.onload = window.onload.extend(function() {
  console.log('bar');
});

// Logs "foo" and "bar"

Demo:http://jsbin.com/akegut/1/edit

演示:http : //jsbin.com/akegut/1/edit

Edit:If you want to extend with multiple functions you can use this:

编辑:如果你想扩展多个功能,你可以使用这个:

Function.prototype.extend = function() {
  var fns = [this].concat([].slice.call(arguments));
  return function() {
    for (var i=0; i<fns.length; i++) {
      fns[i].apply(this, arguments);
    }
  };
};

window.onload = window.onload.extend(function(){...}, function(){...}, ...);

回答by rohit verma

window.addEventListener will not work in IE so use window.attachEvent

window.addEventListener 在 IE 中不起作用,所以使用 window.attachEvent

You can do something like this

你可以做这样的事情

function fun1(){
    // do something
}

function fun2(){
    // do something
}


var addFunctionOnWindowLoad = function(callback){
      if(window.addEventListener){
          window.addEventListener('load',callback,false);
      }else{
          window.attachEvent('onload',callback);
      }
}

addFunctionOnWindowLoad(fun1);
addFunctionOnWindowLoad(fun2);

回答by serkan

If you can not access to the old window.onloadyet still want to keep and add another one, here is the way,

如果您无法访问旧的window.onload但仍想保留并添加另一个,这里是方法,

       function addOnload(fun){
          var last = window.onload;
          window.onload = function(){
            if(last) last();
            fun();
          }
        } 

        addOnload(function(){
            console.log("1");
        });

        addOnload(function(){
            console.log("2");
        });

回答by Tsonev

For some time I used the above solution with:

有一段时间我将上述解决方案用于:

window.onload = function () {
    // first code here...
};

var prev_handler = window.onload;
window.onload = function () {
    if (prev_handler) {
        prev_handler();
    }
    // second code here...
};

However it caused in some cases IE to throw a "stack overflow error" described here in this post: "Stack overflow in line 0" on Internet Explorerand a good write-up on it here

然而,在某些情况下,它会导致 IE 抛出本文中描述的“堆​​栈溢出错误”: Internet Explorer 上的“第 0 行中的堆栈溢出”,并在此处写了一篇很好的文章

After reading through all the suggested solutions and having in mind that jquery is not available, this is what I came up with(further expanding on Khanh TO's solution with some browser compatibility checking) do you think such an implementation would be appropriate:

在阅读了所有建议的解决方案并记住 jquery 不可用后,这就是我想出的(通过一些浏览器兼容性检查进一步扩展 Khanh TO 的解决方案)您认为这样的实现是否合适:

function bindEvent(el, eventName, eventHandler) {
            if (el.addEventListener){
                    el.addEventListener(eventName, eventHandler, false); 
                } else if (el.attachEvent){
                    el.attachEvent("on"+eventName, eventHandler);
                }
            }
      render_errors = function() {
      //do something
      }

      bindEvent(window, "load", render_errors);

      render_errors2 = function() {
      //do something2
      }

      bindEvent(window, "load", render_errors2);

回答by Sebastien Horin

Simply Use (jQuery):

简单使用(jQuery):

$(window).load(function() {
  //code
})

$(window).load(function() {
 //code
})

回答by SadhanaP

By keeping 2 window.onload(), the code in the last chunk is executed.

通过保留2个window.onload(),执行最后一个chunk中的代码。