简体   繁体   English

函数未在 Javascript 中调用

[英]function is not being called in Javascript

new to Javascript and it's quirks. Javascript 的新手,它的怪癖。 Can somebody explain this to me?有人可以向我解释一下吗? it works fine in CodeSandbox, but in VSCode and Chrome I'm hitting this problem:它在 CodeSandbox 中运行良好,但在 VSCode 和 Chrome 中我遇到了这个问题:

setup() function not called in this code:此代码中未调用 setup() 函数:

function init(){
  ...
}

function setup(){
  ...
}

init();
setup();

setup() function being called in this code:此代码中调用的 setup() 函数:

function init(){
  ...
  setup();
}

function setup(){
  ...
}

init();

Why does it execute in the last example, but not in the first?为什么它在最后一个示例中执行,而在第一个示例中不执行?

Just remove this line document.addEventListener('DOMContentLoaded', init) and you're good to go.只需删除这一行document.addEventListener('DOMContentLoaded', init)就可以了。

DOMContentLoaded event is fired when your page is fully loaded and parsed. DOMContentLoaded事件在您的页面完全加载和解析时被触发。 So, the following scenario was happening:因此,发生了以下场景:

init();
setup();
init(); <--- due to DOMContentLoaded event

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM