【问题标题】:How to make a javascript load after other page elements are loaded?加载其他页面元素后如何加载javascript?
【发布时间】:2016-10-11 16:14:24
【问题描述】:

所以我用 HTML 制作了这个剪刀石头布游戏。当页面加载时,它会通过弹出窗口询问用户的输入。问题是在我的任何 div 之前加载弹出窗口,我希望我的所有 html 元素在弹出脚本启动之前都可见。

这是我的代码:

<body>
    <div class="user">
        <div class="container">You choose:</div>
        <div id="userInput"></div>
    </div>
    <div class="computer">
        <div class="container">Computer chooses:</div>
        <div id="computerInput"></div>
    </div>
    <div class="results">
        <div class="container">Results:</div>
        <div id="resultsOutput"></div>
    </div>

    <script type="text/javascript">
            var userInput = prompt("Do you choose rock, paper or scissors?");
        var computerChoice = Math.random();
        if (userInput === "rock" || userInput === "paper" || userInput === "scissors") {
            var userChoice = userInput
        } else {
            userChoice = "Invalid entry, sorry. "
        }

        if (computerChoice < 0.34) {
            computerChoice = "rock";
        } else if (computerChoice <= 0.67) {
            computerChoice = "paper";
        } else {
            computerChoice = "scissors";
        }
        console.log("Computer: " + computerChoice);

        function compare(choice1, choice2) {
            if (userInput === "rock" || userInput === "paper" || userInput === "scissors") {
                if (choice1 === choice2) {
                    return "The result is a tie!";
                } else if (choice1 === "rock") {
                    if (choice2 === "scissors") {
                        return "rock wins";
                    } else {
                        return "paper wins"
                    }
                } else if (choice1 === "paper") {
                    if (choice2 === "rock") {
                        return "paper wins";
                    } else {
                        return "scissors wins";
                    }
                } else if (choice1 === "scissors") {
                    if (choice2 === "rock") {
                        return "rock wins";
                    } else {
                        return "scissors wins"
                    }
                }
            } else {
                return "Results not calculated."
            }
        }
        document.getElementById("userInput").innerHTML = userChoice;
        document.getElementById("computerInput").innerHTML = computerChoice
        compare(userChoice, computerChoice);
        document.getElementById("resultsOutput").innerHTML = compare(userChoice, computerChoice)

    </script>
</body>

【问题讨论】:

标签: javascript html


【解决方案1】:

您的 javascript 在页面的其余部分加载之前执行

您正在尝试使用window.onload,但您做错了。 window.onload 应该是一个函数,像这样:

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

但这仅适用于您只想在页面加载时启动的一项功能。一般来说,最好使用 window.addEventListener 方法,因为您可以使用其中的多个,所有这些都会被执行。

如果您要使用另一个 window.onload = function(){},它将覆盖第一个。

这就是我推荐使用的原因:

window.addEventListener('load',function(){
    //your code here
})

【讨论】:

    【解决方案2】:

    解决方案 1:

    您可以将脚本放在 HTML 文档的底部。这将在 &lt;div&gt; 元素加载后运行您的代码:

    <html>
    <head></head>
    <body>
        <div></div>
        <div></div>
        <div></div>
        ...
        <script>
            // Put your JS code here
        </script>
    </body>
    </html>
    </html>
    

    解决方案 2: 此外,您可以将所有 JS 放在 window.onload 事件监听器中:

    window.onload = function() {
        // Put your JS code here
    };
    

    【讨论】:

      【解决方案3】:

      你可以做三件事。

      1. 在 html 页面中的结束正文标记之前添加脚本标记。
      2. 调用你的逻辑作为你的身体加载事件的一部分

        document.body.onload = function() { console.log('I loaded!'); };

      3. 如果您使用的是 jquery,则可以通过执行以下操作获得与上述相同的结果:

        $(function() { console.log('I loaded!'); })(jQuery);

      【讨论】:

        【解决方案4】:

        你有两个选择 1.在JavaScript中你可以像下面的语法那样做

        document.addEventListener('DOMContentLoaded', function() {
           // your code here
        }, false);
        

        2.在 Jquery 中这样做

        $(document).ready(function(){
        // your code here
        });
        

        【讨论】:

          【解决方案5】:

          也许你可以试试这个……

          <div id="quiz">
              <div class="user ">
                  <div class="container">You choose:</div>
                  <div id="userInput"></div>
              </div>
              <div class="computer">
                  <div class="container">Computer chooses:</div>
                  <div id="computerInput"></div>
              </div>
              <div class="results">
                  <div class="container">Results:</div>
                  <div id="resultsOutput"></div>
              </div>
          </div>
          
          <script type="text/javascript">
          
          
              window.onload = function(){
          
                  if( document.getElementById('quiz') ){
          
                      var userInput = prompt("Do you choose rock, paper or scissors?");
                      var computerChoice = Math.random();
                      if (userInput === "rock" || userInput === "paper" || userInput === "scissors") {
                          var userChoice = userInput
                      } else {
                          userChoice = "Invalid entry, sorry. "
                      }
          
                      if (computerChoice < 0.34) {
                          computerChoice = "rock";
                      } else if (computerChoice <= 0.67) {
                          computerChoice = "paper";
                      } else {
                          computerChoice = "scissors";
                      }
          
                      console.log("Computer: " + computerChoice);
                      document.getElementById("computerInput").innerHTML = computerChoice;
                      if( userChoice !== undefined ){
                           document.getElementById("userInput").innerHTML = userChoice;
                           compare(userChoice, computerChoice);
                           document.getElementById("resultsOutput").innerHTML = compare(userChoice, computerChoice)
                      }
          
                  }
          
              }
          
          
              function compare(choice1, choice2) {
          
                  if (userInput === "rock" || userInput === "paper" || userInput === "scissors") {
                      if (choice1 === choice2) {
                          return "The result is a tie!";
                      } else if (choice1 === "rock") {
                          if (choice2 === "scissors") {
                              return "rock wins";
                          } else {
                              return "paper wins"
                          }
                      } else if (choice1 === "paper") {
                          if (choice2 === "rock") {
                              return "paper wins";
                          } else {
                              return "scissors wins";
                          }
                      } else if (choice1 === "scissors") {
                          if (choice2 === "rock") {
                              return "rock wins";
                          } else {
                              return "scissors wins"
                          }
                      }
                  } else {
                      return "Results not calculated."
                  }
              }
          
          
          </script>
          

          【讨论】:

            【解决方案6】:

            如果你使用 jQuery,Hero1134 是完全正确的。如果你使用 jQuery,你可能应该使用

            $(document).ready(function(){ })
            

            .ready 函数将在 DOM 准备好后立即执行(html 元素已加载并准备好对其进行处理)。如果您使用 .load ,您将等待页面上的每个元素全部加载,因此您必须等待大图像等待加载。在某些页面上,这两种方法之间的差异可能只有几秒钟!

            您也可以改为在文件末尾运行脚本

            <body>
              <divs />
              <script>var userInput = prompt("Do you choose rock, paper or scissors?"); ...</script>
            </body>
            

            因此元素将可用于脚本。

            如果您只想使用没有依赖关系的普通旧 javascript,并且希望在文件顶部包含 js,您可以修复此行

            window.onload = var userInput = prompt("Do you choose rock, paper or scissors?"); ...
            

            改为这样

            window.onload = function(){ var userInput = prompt("Do you choose rock, paper or scissors?"); ... }
            

            【讨论】:

              【解决方案7】:

              使用函数

               $(window).load(function () {
              
              });
              

              【讨论】:

              • 什么?为什么?这是没有意义的
              • ReferenceError $ 未定义
              • window.addEventListener('load',function(){}) 是正确的方法。
              • stackoverflow.com/questions/4584373/…。有关更多信息,请参阅此帖子。希望对您有所帮助。
              • 它仍然可以工作。我的意思是我现在也在使用它。我的大部分代码都在 javascript 中。
              【解决方案8】:

              您可以在执行 JavaScript 之前使用 JQuery 加载 HTML 页面。类似的东西可能会起作用。

              $(document).ready(init);
              function init(){
               //your JavaScript code here 
              }
              

              【讨论】:

              • 一切的答案都不是jQuery!!
              • 我同意,但我想这是另一种方式,我认为它会有所帮助!
              • 我真的不明白。 JQuery 不也是 Javascript 的库吗?
              • 它是一个 JavaScript 库,使您能够用更少的代码行做同样的事情
              • @Hero1134:加载一个臃肿的库只是为了让你的代码在 DOM 准备好时运行是愚蠢的。
              猜你喜欢
              • 2011-03-05
              • 1970-01-01
              • 2019-08-09
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-05-26
              相关资源
              最近更新 更多