Code works in Codepen, but not with my desktop fil

2020-04-14 07:18发布

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:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="javascript/script.js"></script>
</head>
<body>

  <div id="content1">This is content 1  </div>
  <div id="content2">This is content 2  </div>
  <div id="content3">This is content 3  </div>

</body>
</html>

And for my javascript section i have:

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

When I run this in CodePen, or even on the code editor on this website, it works fine. But it doesn't work when I use the files on my desktop (index.html, script.js I do believe the folder structure is correct (script.js is in the javascript folder.)

Thank you all

2条回答
The star\"
2楼-- · 2020-04-14 07:22

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

$(document).ready(function (){ 
// your code goes here
 });
查看更多
Animai°情兽
3楼-- · 2020-04-14 07:43

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();
});
查看更多
登录 后发表回答