简体   繁体   中英

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

I tried making the javascript into a separate file called 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:

<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. The browser needs to parse the HTML before he can access the DOM via javascript , in your case:
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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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