我有一个函数,foo我想添加,window.onload但我的问题是已经有另一个函数bar,设置为window.onload.如何附加两个功能.我没有权限改变bar添加的逻辑,window.onload因此我无法使用范例addEvent(…).在所有情况下都会像以下一样工作吗?
<script>
$(window).load(foo(){
//my code here
});
</script>
//lots of html
//potentially this happens before or after my above script
<script>
window.onload = bar();
otherFunction(){
//other function code here
};
</script>
Run Code Online (Sandbox Code Playgroud)
由于您使用的是jQuery,因此这不是问题.您可以$(window).load(...)多次调用它,它不会扼杀以前绑定的事件处理程序.
此函数将匿名函数作为参数,在触发load事件后执行该参数.例如
$(window).load(function() {alert('the window has loaded');});
Run Code Online (Sandbox Code Playgroud)
JQuery .load()处理程序的文档:https://api.jquery.com/load-event.
作为参考,将使用等效的"vanilla"JS window.addEventListener.
更新
而不是.load事件,使用.on('load,':
$(window).on('load', function() { alert('This is better'); });
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅/sf/answers/2654113521/.