简体   繁体   English

Javascript:使用外部脚本

[英]Javascript: Using External Scripts

I am trying to import a simple script into an HTML doc. 我正在尝试将简单的脚本导入HTML文档。 It won't work and I have no idea what I am doing wrong. 它不会工作,我不知道我做错了。

Name of external script--> (function.js) 外部脚本的名称->(function.js)

window.onload = myFunction;

       function myFunction() 
       {
             document.getElementById("HERE").innerHTML = "message";
       }

name of HTML doc--> (attributes.html) HTML doc的名称->(attributes.html)

<!DOCTYPEhtml>

    <html>
    <head>

         <title> This is an example of using an external script</title> 
            <script type ="text/javascript" src= "function.js"></script>
    </head>
    <body>

          <h1 id="HERE"> 
          </h1>

    </body>
    </html>

I think that the body on load event fires too early, before js file go running. 我认为加载事件的主体在js文件运行之前触发得太早。 Try to use "document.body.onload" at least of "window.onload". 尝试至少在“ window.onload”中使用“ document.body.onload”。 Try to use "document.attachEvent": 尝试使用“ document.attachEvent”:

document.attachEvent(document.body, "load", myFunction)
<html>
<head>

     <title> This is an example of using an external script</title> 
        <script type ="text/javascript" src= "function.js"></script>
</head>
<body>

      <h1 id="HERE"> 
      </h1>

     <script>myFunction() </script>
</body>
</html>

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

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