一个函数执行两个函数但只执行一个函数?

问题描述 投票:0回答:5

我尝试在使用window.onload加载页面时使用一个函数来执行两个函数,我遇到的问题是该函数(myFunc)仅执行顶部的第一个函数(Func1),但不执行(Func2) ,该函数看起来像这样

window.onload = function myFunc(){
    return Func1(); 
    return Func2(); 
} 

那么我怎样才能同时执行它们呢?

javascript html css
5个回答
1
投票

试试这个:)

确保在调用函数之前定义函数,这是一个很好的做法

//Arrow function and remove the return

const Func1 = () => {
  console.log('This is Func1');
}
const Func2 = () => {
  console.log('This is Func2');
}

window.onload = myFunc = () => {
  Func1();
  Func2();
}


0
投票

不要

return
因为
return
会失效

window.onload = function myFunc(){
    Func1(); 
    Func2(); 
}

0
投票

删除 return 关键字,然后按原样运行该函数。


0
投票

参考:https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

window.onload = function() {
  Func1();
  Func2();
};

无需返回语句和命名函数。它应该触发这两个函数,如果没有,请通过放置断点或添加调试器来确保代码更改反映在源代码中;函数内部。还要检查两个函数体是否执行相同的操作,以便您得出第二个函数体未执行的结论。


0
投票

js引擎在return关键字上完成函数的执行。 所以不要使用 return 关键字来执行这两个函数

© www.soinside.com 2019 - 2024. All rights reserved.