外部JavaScript未运行,不写入文档

External JavaScript Not Running, does not write to document

本文关键字:文档 JavaScript 运行 外部      更新时间:2023-09-26

我正试图使用外部JavaScript文件将"Hello World"写入HTML页面。

然而,由于某些原因,它不起作用,我在内联中尝试了相同的函数和命令,它起作用了,但当它使用外部JavaScript文件时就不起作用了。我在JS文件中注释的部分是我之前尝试使用的方法。当我从标题和内联运行脚本时,这些行可以工作。感谢

Html文件:

<html>
    <head>
    </head>
<body>
    <p id="external">
        <script type="text/javascript" src="hello.js">
            externalFunction();
        </script>
    </p>
    <script type="txt/javascript" src="hello.js"></script>
</body>
</html>

JavaScript文件

function externalFunction() 
        {
         var t2 = document.getElementById("external");
            t2.innerHTML = "Hello World!!!"
         /*document.getElementById("external").innerHTML = 
         "Hello World!!!";*/
        }

通常,您希望将JavaScript放在页面底部,因为它通常会减少页面的显示时间。有时您可以在头中找到导入的库,但无论哪种方式,您都需要在使用函数之前声明它们。

http://www.w3schools.com/js/js_whereto.asp

index.html

<!DOCTYPE html>
<html>
<head>
  <!-- You could put this here and it would still work -->
  <!-- But it is good practice to put it at the bottom -->
  <!--<script src="hello.js"></script>-->
</head>
<body>
  <p id="external">Hi</p>
  <!-- This first -->
  <script src="hello.js"></script>
  <!-- Then you can call it -->
  <script type="text/javascript">
    externalFunction();
  </script>
</body>
</html>

hello.js

function externalFunction() {
  document.getElementById("external").innerHTML = "Hello World!!!";
}

Plunker在这里。

希望这能有所帮助。

具有SRC值的脚本标记不会运行内容。将其拆分为两个脚本标记。一个用于include,一个用于函数调用。并确保包含在通话之前。

使用onload eventListener使其变得简单

<script>
   window.onload = function() {
      externalFunction();
   }
</script>

您试图在加载函数之前调用它。

将加载脚本放在声明上方:

<html>
    <head>
<script type="txt/javascript" src="hello.js"></script>
    </head>
<body>
    <p id="external">
        <script type="text/javascript">
            externalFunction();
        </script>
    </p>

</body>
</html>

你还有一个打字错误:

 <script type="txt/javascript" src="hello.js"></script>

应为:

<script type="text/javascript" src="hello.js"></script>

脚本类型需要是"text/javascript",而不是"txt/javascript"。