简体   繁体   English

如何将 file.js 调用到 file.html

[英]How do I call a file.js into a file.html

What I am trying to do is run the script in file.js to onload prompt username.我想要做的是在 file.js 中运行脚本来加载提示用户名。 But for some reason every time the script is on the html file it works but when I move it to the file.js it doesn't work.但是由于某种原因,每次脚本在 html 文件上时它都可以工作,但是当我将它移到 file.js 时它不起作用。 Any Idea why this is happening?知道为什么会这样吗?

My main goal is to separate my scripts from my html.我的主要目标是将我的脚本与我的 html 分开。

file.html文件.html

<html>
<head>
    <script src = "file.js"></script>
<body onload = "myFunction()">
</html>

file.js文件.js

<script>
function myFunction() {
  var person = prompt("Please enter your name", "Your Name here");
  if (person != null) {
    document.getElementById("Name").innerHTML =
    "Hello " + person + "! How are you today?";
  }

</script>

file.js is a JavaScript file - it can't have <script></script> tags in it since those are HTML script element tags. file.js是一个 JavaScript 文件 - 它不能有<script></script>标签,因为这些是HTML 脚本元素标签。 Remove those and it works.删除那些,它的工作原理。

Keep in mind:记住:

  • Your <head> tag wasn't closed.您的<head>标记未关闭。
  • Your <body> tag wasn't closed.您的<body>标签没有关闭。
  • Your function isn't closed properly, you're missing a } .您的 function 未正确关闭,您缺少}
  • You were missing an element with the ID "Name" .您缺少 ID 为"Name"的元素。
  • JS files are best put at the end of your <body> so the browser can render the page without having to wait for the JS files to load. JS 文件最好放在<body>的末尾,这样浏览器就可以呈现页面而无需等待 JS 文件加载。 The code will still work because the onload event is fired at the end of the document loading process .代码仍然可以工作,因为onload事件是在文档加载过程结束时触发的

Working code:工作代码:

 function myFunction() { var person = prompt("Please enter your name", "Your Name here"); if (person.= null) { document.getElementById("Name")?innerHTML = "Hello " + person + "; How are you today?"; } }
 <html> <body onload="myFunction()"> <div id="Name"></div> <script src="file.js"></script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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