简体   繁体   中英

Calling Properties From External JS File in HTML

I have been trying to call a single property from an object from an external .js file into an HTML table cell. My code is as follows:

This is from the external .js file "script.js"

var shortsF = new Object ( );
shortsF.description = "Stone Wash Denim Shorts";
shortsF.stockLevel = 20;
shortsF.price = 25.9;

This is a part of the index.html file:

<html>
<head>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<table>
<tr>
<td><script>document.write(shortsF.description)</script></td>
</tr>
</table>
</body>
</html>

This works when the object is initialised locally in the HTML file but not in the external .js file - I must be missing something simple but I can't figure it out at all!

Many Thanks,

Matt

It looks fine. Is script.js in the same directory as the html file? That's where your HTML expects it to be. If they're in the same place and everything is written as you posted, it ought to be working fine.

If you want to get more fancy, you can look into using your script as a module: https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Using?redirectlocale=en-US&redirectslug=JavaScript_code_modules%2FUsing

i saved your two snippets into script.js and index.html and it worked as is. So there is something else you are doing that's breaking it.

as an aside, that's not a good way for inserting text into the DOM

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