2016-07-05 50 views
3

我很新的編碼,我試圖完成Codecademy的JavaScript課程。我已經學習了一些關於HTML/CSS的知識,而且我幾乎完成了JavaScript。我研究過有類似問題的人,但這些解決方案通常涉及JQuery,我從未學過。爲什麼我的JavaScript鏈接不能從HTML中調用?

這裏是我的HTML(的index.html):

<!DOCTYPE html> 
<html> 
    <head> 
    <script type="text/javascript" src="main.js"></script> 
    </head> 
    <body> 
    </body> 
</html> 

這裏是我的JavaScript的開頭:

alert(); 

// Acquire character's name and check to make sure it's a string 
var charName = prompt("NASA Receptionist: 'Welcome to Mission Control. 
May I have your last name, please?'"); 

var nameCheck = function(charName) { 
    while (typeof charName === "number") { 
     charName = prompt("NASA Receptionist: 'Surely, your name is not 
a number... Please, may I have your last name?'"); 
    } 
}; 

nameCheck(charName); 

注意:index.html的是在同一文件夾中main.js

當我打開index.html時,沒有任何反應,甚至沒有打開alert()。我錯過了什麼嗎?

+1

你覺得在控制檯任何錯誤? – Rayon

+0

我不完全確定這意味着什麼。我正在使用Sublime Text 2創建文件。我知道如何查看我的文件的唯一方法是嘗試在我的Web瀏覽器中運行它... – Goeff

+0

Google Developer Tools中存在「意外令牌」錯誤。我拿了;出我的while循環,並修復它! – Goeff

回答

6

您的腳本中有錯誤,因爲無法使用轉義斜槓在多行中生成javascript語句。

我得到這個錯誤:

SyntaxError: unterminated string literal

var charName = prompt("NASA Receptionist: 'Welcome to Mission Control.

下面是修改代碼:

alert(); 

    // Acquire character's name and check to make sure it's a string 
    //The \r\n\ will format the string in prompt and make it appear in new line 
    var charName = prompt("NASA Receptionist: 'Welcome to Mission Control. \ 
         \r\n\May I have your last name, please?'"); 

    var nameCheck = function(charName) { 
     while (typeof charName === "number") { 
      charName = prompt("NASA Receptionist: 'Surely, your name is not \ 
           \r\n\a number... Please, may I have your last name?'"); 
     } 
    }; 

    nameCheck(charName); 
+2

關閉....但可能不是什麼OP後。由於字符串第二行的前導空格(https://jsfiddle.net/3mawcL9y/),警報中的文本格式不正確。我建議使用換行符替代'\ r \ n'(https:// jsfiddle.net/3mawcL9y/1/) –

+0

@JonP我可以使用\ n \來達到同樣的效果,我可以嗎? – shivgre

+1

'r \ n \是最安全的選擇。不同的操作系統'使用不同的行結束字符! (http://stackoverflow.com/questions/15433188/r-n-r-n-what-is-the-difference-between-them) –

2

檢查瀏覽器的源文件main.js是否加載。

使用的警報(「=裝=」)檢查警報被稱爲與否

+0

即使是一個alert();會顯示一個空警報 – shivgre

+0

而且我看到upvote .. _WHY_? – Rayon

2

如果你甚至沒有得到語法錯誤,那麼我想你也許引用main.js不正確。你確定你在index.html的同一個目錄下有這個嗎? 另外,每次我運行它,typeof方法返回「字符串」,無論我輸入一個數字或不。

alert(typeof charName);

+0

感謝您揭露此事。以後我得弄清楚別的。現在,我需要修復我的html沒有訪問我的js。我的main.js文件與我的index.html位於同一個文件夾中... – Goeff

相關問題