我有一个函数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>
答案 0 :(得分:5)
这是一个非问题,因为你正在使用jQuery。你可以多次调用$(window).load(...)
,它不会扼杀以前绑定的事件处理程序。
此函数将匿名函数作为参数,在触发load事件后执行该参数。 e.g。
$(window).load(function() {alert('the window has loaded');});
.load()
处理程序的JQuery文档:https://api.jquery.com/load-event。
作为参考,等效的“vanilla”JS将使用window.addEventListener
。
<强>更新强>
使用.load
:
.on('load,'
事件
$(window).on('load', function() { alert('This is better'); });
答案 1 :(得分:3)
无法附加函数,但您可以使用addEventListener
然后为load
事件注册多个函数:
window.addEventListener("load",a);
window.addEventListener("load",b);
function a(){
alert("one");
}
function b(){
alert("two");
}
答案 2 :(得分:-1)
<!doctype html>
<html>
<head>
<meta http-equiv='content-type' content='text/hmtl; charset=utf-8'/>
<script type='text/javascript'>
window.addEventListener("load",foo);
window.addEventListener("load",bar);
function foo(){
alert("this");
}
function bar(){
alert("that");
}
</script>
</head>
<body>
</body>
</html>