2015-09-07 34 views
1

我在HTML頁面中有一個簡單的JavaScript腳本,當它包含在標題中時工作,但是當我嘗試將它放入單獨的文件並導入它時,它什麼都不做。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);

+0

檢查您的路徑。你可以創建一個jsdille鏈接 –

回答

1

只需設置src =「js/script.js」>。一切都會好起來的。

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

該錯誤的原因是「/」將搜索script.js的磁盤根文件夾。

使用SRC = 「/ JS /的script.js」

  • 代碼文件夾:C:/程序/代碼
  • 搜索文件夾:C:/js/script.js

使用SRC = 「JS /的script.js」

  • 代碼文件夾:C:/程序/代碼
  • 搜索文件夾:C:/語言程序ms/js/script.js
+0

哇...我無言以對。即使當我右鍵單擊Microsoft Expression Web 4中的鏈接並單擊「Follow Code Hyperlink」時,它將我帶到腳本中。謝謝你。 –

1

您需要檢查的路徑js文件是可以或不可以的。似乎在您提供的位置找不到文件。如果file not found錯誤(404 error)即將到期,您可以在Chrome瀏覽器開發人員工具enter image description here中查看控制檯錯誤。

相關問題