html页面中的javascript脚本块在标题中工作,但不在外部文件中

时间:2015-09-07 06:06:21

标签: javascript jquery html

我的HTML页面中有一个简单的javascript脚本,当它包含在标题中时可以正常运行,但是当我尝试将它放在一个单独的文件中并导入它时,它没有做任何事情。

这是html页面:

<!DOCTYPE html>
<html>
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

<style>
div#test{ border:#000 1px solid; padding:10px 40px 40px 40px; }
</style>

<script type="text/javascript" src="/js/script.js"> </script>

</head>

<body>

<h2 id="test_status"></h2>
<div id="test"></div>

</body>

</html>

和我的script.js代码:

var pos = 0,
  test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
var questions = [
  ["What is 10 + 4?", "12", "14", "16", "B"],
  ["What is 20 - 9?", "7", "13", "11", "C"],
  ["What is 7 x 3?", "21", "24", "25", "A"],
  ["What is 8 / 2?", "10", "2", "4", "C"]
];

function _(x) {
  return document.getElementById(x);
}

function renderQuestion() {
  test = _("test");
  if (pos >= questions.length) {
    test.innerHTML = "<h2>You got " + correct + " of " + questions.length + " questions correct</h2>";
    _("test_status").innerHTML = "Test Completed";
    pos = 0;
    correct = 0;
    return false;
  }
  _("test_status").innerHTML = "Question " + (pos + 1) + " of " + questions.length;
  question = questions[pos][0];
  chA = questions[pos][1];
  chB = questions[pos][2];
  chC = questions[pos][3];
  test.innerHTML = "<h3>" + question + "</h3>";
  test.innerHTML += "<input type='radio' name='choices' value='A'> " + chA + "<br>";
  test.innerHTML += "<input type='radio' name='choices' value='B'> " + chB + "<br>";
  test.innerHTML += "<input type='radio' name='choices' value='C'> " + chC + "<br><br>";
  test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";
}

function checkAnswer() {
  choices = document.getElementsByName("choices");
  for (var i = 0; i < choices.length; i++) {
    if (choices[i].checked) {
      choice = choices[i].value;
    }
  }
  if (choice == questions[pos][4]) {
    correct++;
  }
  pos++;
  renderQuestion();
}
window.addEventListener("load", renderQuestion, false);

2 个答案:

答案 0 :(得分:1)

您需要检查js文件的路径是否正常。在您提供的位置似乎找不到文件。如果file not found错误(404 error)即将来临,您可以在Chrome浏览器开发者工具enter image description here中检查控制台错误。

答案 1 :(得分:1)

只需设置src =&#34; js / script.js&#34;&gt;。一切都会好的。

<script type="text/javascript" src="js/script.js"> </script>

这个错误的原因是&#34; /&#34;将在Disk根文件夹中搜索script.js。

使用src =&#34; /js/script.js"

  • 代码文件夹:C:/ Programs / code
  • 搜索文件夹:C:/js/script.js

使用src =&#34; js / script.js&#34;

  • 代码文件夹:C:/ Programs / code
  • 搜索文件夹:C:/Programs/js/script.js