简体   繁体   中英

Locally sourcing Javascript in HTML

Extreme beginner here guys so please explain as easily as possible.
I've read multiple variations of this and still am unable to figure it out, any help is greatly appreciated.

What I am wanting is a local environment to be able to learn HTML & javascript, but cannot get the script source inside HTML to correctly reference the .js file sitting in the exact same folder as the .html file.
I am testing in a Chrome browser just referencing the .html file on my local machine via file:///C:/JavaScript/Index.html.

2 files(index.html and JS.js), both located locally on C:\\Javascript

HTML Code:

<!doctype html>
<head>
    <title>Title in browser tab</title>
</head>
<body>
"Text on the page"
<script src="C:\JavaScript\JS.js"></script>
</body>
</html>

-Based on what I read, if they are in the same folder I should be able to just reference <Script src="JS.js"> as there is no folder structure to look through, is that correct?

-I've also tried to absolute path via <script src="file:///C:/JavaScript/JS.js"> and related versions of <Script src="C:\\Javascript\\JS.js"> that do not work either.

In my JS.js file, I have nothing but alert(); to test functionality, as my reasoning for incorrect sourcing. If I simply write <script>alert();</script> without referencing any outside source, the alert works as planned.

Thank you in advance!

I'd recommend popping open Chrome's Developer Tools to see where the issue may lie (and, if you're new to development, these are tools that are built into Chrome that will make your life so much easier).

Your assumption about not requiring a path should be correct: if you're referencing another file that lives in the same directory, omitting a full path will cause the browser to assume the path is relative (eg "right next to") to the current file:

<!doctype html>
<head>
    <title>Title in browser tab</title>
</head>
<body>
"Text on the page"
<script src="JS.js"></script>
</body>
</html>

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