Code works in Codepen, but not with my desktop files

守給你的承諾、 提交于 2019-12-02 00:48:03

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();
});

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

$(document).ready(function (){ 
// your code goes here
 });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!