简体   繁体   中英

javascript only works in <script> tags, not js file

I'm making a clickable dropdown menu. But when I run the javascript in its own js file the js doesn't work. However, when I put the javascript in tags in my html document, the menu works perfectly fine. Does anyone know how to make the javascript work in its own js file?

function myFunction() {
 document.getElementById("myDropdown").classList.toggle("show");
}

window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
};

Try

document.addEventListener('DOMContentLoaded', function() {
  // do stuff here

}, false);

You need to create a JS file called script.js and then add this to HTML document before closing body tag:

<script src="script.js"></script>

I assume you are not including the script correctly. Check your console for errors.

Also, if you are including script in the head section, it could be loaded before the HTML, therefore the selectors possibly could not be found. Including script at the end of the HTML document (before closing body tag) would assure the document is loaded before script is executed.

In order to execute JavaScript from an external file, you will need to include the file in the HTML file using something like the following:

<head>
        <script type="text/javascript" src="location/of/file/filename.js"></script>
</head>

From there, make the HTML element you are using call the JavaScript function you are wishing to execute.

Example:

<button onclick="functionName()">Click!</button>

This will then go to the function you are calling in the JavaScript file and execute the body of the function.

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