我有两个问题(按顺序排列)?
我正在重构两组代码。每个都有一个加载。
两者都会在网站上自行运行,但我不希望它们覆盖彼此的加载。
所以我有等价的:
window.onload=function(){ alert("foo")};
和
window.onload=function(){ alert("bar")};
在两个文件中。
为了避免一个覆盖另一个的 window.onload 分配,我将它们重构为:
window.onload+=function(){ alert("foo")};
和
window.onload+=function(){ alert("bar")};
但似乎两者都没有发生。
既然它似乎可以帮助我理解情况并且通常是一项不错的技能,那么如何向函数变量添加附加函数? (它和 onload 一样,还是 onload 是一个特殊情况?它给我的印象就像是可能有特殊情况的东西。)
所以如果我有...
var Varrick = function(){ alert("Do the thing!");}
我有
var Zhu_li = function (){ alert("Did the thing."); }
该命令实际上是什么
var Varrick = Varrick + Zhuli.
所以...
Varrick(); // Alerts "Do the thing!" then alerts "Did the thing."
注意:我想在不依赖 jQuery 的情况下执行此操作。
最佳答案
这就是为什么分配给 on-
属性通常不是一个好主意的原因之一 - 如果该属性上以前存在任何内容,它将被覆盖,因此只有最新的处理程序才会触发。 (并且不要尝试 +=
相互调用)
尝试添加 DOMContentLoaded
监听器:
function foo() {
console.log('foo');
}
function bar() {
console.log('bar');
}
document.addEventListener("DOMContentLoaded", foo);
document.addEventListener("DOMContentLoaded", bar);
how do I add additional functions to a function variable?
如果您必须只有一个监听器,则只需调用监听器中的两个函数即可:
document.addEventListener("DOMContentLoaded", () => {
foo();
bar();
});
这就像
window.onload = function(){
foo();
bar();
};
(但是,通常最好使用 addEventListener
)
关于javascript - 重构 onload 以添加第二个功能?奖金 : what about adding second functions to variables in general?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51093454/