简体   繁体   English

javascript仅适用于<script> tags, not js file

[英]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. 但是,当我在自己的js文件中运行javascript时,js无法正常工作。 However, when I put the javascript in tags in my html document, the menu works perfectly fine. 但是,当我将javascript放在html文档的标记中时,菜单运行正常。 Does anyone know how to make the javascript work in its own js file? 有谁知道如何使javascript在其自己的js文件中工作?

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.js的JS文件,然后在关闭body标签之前将其添加到HTML文档中:

<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. 另外,如果您在头部分中包含脚本,则可以在HTML之前加载脚本,因此可能找不到选择器。 Including script at the end of the HTML document (before closing body tag) would assure the document is loaded before script is executed. 在HTML文档末尾(在关闭body标签之前)包含脚本将确保在执行脚本之前加载文档。

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: 为了从外部文件执行JavaScript,您需要使用类似以下内容的HTML文件中包含该文件:

<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. 从那里,使您正在使用的HTML元素调用您希望执行的JavaScript函数。

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. 然后将转到您在JavaScript文件中调用的函数并执行该函数的主体。

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

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