简体   繁体   English

HTML链接到外部JavaScript无法正常工作

[英]HTML link to external javascript not working

I was basically implementing this from W3School: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_accordion_symbol 我基本上是从W3School实现这个: https ://www.w3schools.com/howto/tryit.asp filenamename-tryhow_js_accordion_symbol

I tried making the javascript into a separate file called accordion.js 我尝试将javascript变成一个名为accordion.js的独立文件

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    } 
  }
}

and tried calling the javascript file via HTML doing this: 并尝试通过HTML调用javascript文件执行此操作:

<script type="text/javascript" src="accordion.js"></script>

Can anyone tell me what I can do to fix this and help explain why it didn't work? 谁能告诉我我能做些什么来解决这个问题,并帮助解释为什么它不起作用?

Just to add a little more to the answer given in the comments : 只是为了在评论中给出的答案增加一点:

Here is a long answer on the subject : Load and execution sequence of a web page? 这是一个关于这个主题的长篇答案: 网页的加载和执行顺序? .

But, if we simplify, the parsing of the HTML is synchronous. 但是,如果我们简化,HTML的解析是同步的。 The browser needs to parse the HTML before he can access the DOM via javascript , in your case: 在您通过javascript访问DOM之前,浏览器需要解析HTML,在您的情况下:
var acc=document.getElementsByClassName("accordion");

That is why, and to prevent bugs like you had, that $(document).ready() from jQuery is very famous https://learn.jquery.com/using-jquery-core/document-ready/ 这就是为什么,并且为了防止像你这样的bug,来自jQuery $(document).ready()是非常有名的https://learn.jquery.com/using-jquery-core/document-ready/

根据您可能获得的错误,听起来JS文件可能不在同一目录中。

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

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