繁体   English   中英

html 元素在 Javascript 文件之后加载,即使<script> tag is at the bottom of the <body> tag

[英]html elements load after Javascript file even though the <script> tag is at the bottom of the <body> tag

我遇到了 Javascript 问题。 HTML 元素一直在等待 javascript 文件,即使脚本标记位于页面底部。 元素不会更新,如果更改并在 5 秒后消失这是代码: 在此处输入图片说明

代码:

<!DOCTYPE html>
<html>
<head>
    <title>Javascript</title>
    <link rel="stylesheet" type="text/css" href="">
</head>
<body>
    <h1>javascript in HTML</h1>
    <p>HElllllooooo</p>




    <script type="text/javascript">
        var age  = prompt("What is your age?");

        if (Number(age) < 18) {
            alert("Sorry, you are too young to drive this car. Powering off ");
        } else if (Number(age) > 18) {
            alert("Powering on. Enjoy the ride!");
        } else if (Number(age) === 18 ) {
            alert("Congratulations on your first year of driving. Enjoy the 
                  ride!"); 
        }
    </script>
</body>
</html>

prompt是同步的,因此阻止执行直到返回。 这就是为什么第二行(以及其余各行)在prompt返回之前不执行的原因。

至于位于底部的script标签,请按以下方式实施:

window.onload = myFunction

您可能需要将其添加到其自己的匿名函数中,该函数可以设置为在onload上运行;

理论上应该可以正常工作:

(function () {
  var age = prompt("What is your age?");

  if (Number(age) < 18) {
    alert("...");
  } else if (Number(age) > 18) {
    alert("...");
  } else if (Number(age) === 18) {
    alert("...");
  } else {
    // ... fallback logic?
  }
})();

或者,正如已经回答的那样,您可能需要将代码包装在window.load var中。 也是一个匿名函数。

只需像这样在<body>上添加一个onload属性,无论如何:

<body onload="carsGoBrr()">

然后定义函数:

function carsGoBrr() {
  var age = prompt("What is your age?");

  if (Number(age) < 18) {
    alert("Sorry, you are too young to drive this car. Powering off ");
  } else if (Number(age) > 18) {
    alert("Powering on. Enjoy the ride!");
  } else if (Number(age) === 18 ) {
     alert("Congratulations on your first year of driving. Enjoy the ride!"); 
  }
}

完整代码(按照我的编码风格;)):

<!DOCTYPE html>
<html>
  <head>
    <title>Javascript</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <h1>javascript in HTML</h1>
    <p>HElllllooooo</p>
    <script type="text/javascript">
      function carsGoBrr() {
        var age = prompt("What is your age?");

        if (Number(age) < 18) {
          alert("Sorry, you are too young to drive this car. Powering off ");
        } else if (Number(age) > 18) {
          alert("Powering on. Enjoy the ride!");
        } else if (Number(age) === 18 ) {
          alert("Congratulations on your first year of driving. Enjoy the ride!"); 
        }
      }
    </script>
</body>
</html>

您是否尝试过将条件放入window.onload函数中?

window.onload = function(){
    // code goes here
};

暂无
暂无

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

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