简体   繁体   中英

Why won't my JavaScript link work when called from HTML?

I'm pretty new to coding, and I'm trying to complete Codecademy's Javascript course. I've learned a little bit about HTML/CSS and I'm almost done with JavaScript. I've researched people having similar problems, but those solutions typically involve JQuery, which I haven't learned.

Here is my HTML (index.html):

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

Here is the beginning of my 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);

NOTE: index.html is in the same folder as main.js

When I open the index.html, nothing happens, not even the opening alert(). Am I missing something?

You have error in your script as you cannot make javascript statements in multiple lines without using escaping slash .

I was getting this error :

SyntaxError: unterminated string literal

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

Here is the modified code :

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

Check in browser source file whether main.js is loaded.

use alert("= loaded =") to check alert is called or not

If you are not even getting the syntax error, then I think you maybe referencing main.js incorrectly. Are you sure you have this in the same directory as index.html. Also, each time I run it, the typeof method returns "string", no matter if I enter a number or not.

 alert(typeof charName); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM