Code works in Codepen, but not with my desktop files

后端 未结 2 608
盖世英雄少女心
盖世英雄少女心 2021-01-22 06:09

I\'m trying to run a simple few lines of code using an index.html file and a script.js file, nothing else.

In the HTML file, I have doctype html:



        
相关标签:
2条回答
  • 2021-01-22 06:24

    wrap your code in this function to execute it if the document is ready.

    $(document).ready(function (){ 
    // your code goes here
     });
    
    0 讨论(0)
  • 2021-01-22 06:37

    Move your script tag just before the closing of the body tag:

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

    This way the DOM will be available when your script runs.

    If you prefer to keep your script in the head part, then wrap your code in a DOMContentLoaded event handler:

    document.addEventListener("DOMContentLoaded", function() {
        var elems = $("div");
        if (elems.length) {
          var keep = Math.floor(Math.random() * elems.length);
          for (var i = 0; i < elems.length; ++i) {
            if (i !== keep) {
              $(elems[i]).hide();
            }
          }
        }
    });
    

    ... so to have your code run when the DOM is ready.

    You did not tag your question with jquery, but as you seem to use it, you can use this shorter code for doing essentially the same as above:

    $(function() {
        var $elems = $("div").hide(),
        $elems.eq(Math.floor(Math.random() * $elems.length)).show();
    });
    
    0 讨论(0)
提交回复
热议问题