簡體   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