Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

javascript - Code works in Codepen, but not with my desktop files

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...