代码可在Codepen中使用,但不适用于我的桌面文件 [英] Code works in Codepen, but not with my desktop files

查看:120
本文介绍了代码可在Codepen中使用,但不适用于我的桌面文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用index.html文件和script.js文件运行简单的几行代码,

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

在HTML文件中,我的文档类型为html:

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>

对于我的javascript部分,我有:

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

当我在CodePen中甚至在此网站上的代码编辑器中运行此程序时,它都可以正常工作.但是当我在桌面上使用文件(index.html,script.js我确实认为文件夹结构正确(script.js在javascript文件夹中)时,该功能就无效)

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.)

谢谢大家

推荐答案

在body标记关闭之前移动脚本标记:

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

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

这样,当脚本运行时DOM将可用.

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

如果您希望将脚本保留在head部分中,则将代码包装在DOMContentLoaded事件处理程序中:

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

...以便在DOM准备就绪时运行您的代码.

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

您没有使用jquery标记问题,但是您似乎可以使用该较短的代码来完成与上述相同的操作:

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

这篇关于代码可在Codepen中使用,但不适用于我的桌面文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆