【问题标题】:External JavaScript Not Running, does not write to document外部 JavaScript 未运行,未写入文档
【发布时间】:2015-01-05 10:39:54
【问题描述】:

我正在尝试使用外部 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!!!";*/

        }

【问题讨论】:

  • 声明后是否运行了函数externalFunction()
  • 为了使函数工作,你需要调用它。声明后调用函数,它会工作。
  • 好的,开始工作了,谢谢
  • 两次调用脚本不是多余的吗?我被告知总是在正文末尾添加

标签: javascript html external


【解决方案1】:

一般来说,您希望将 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>

你好.js

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

Plunkerhere.

希望这会有所帮助。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      使用 onload eventListener 让它变得简单

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

      【讨论】:

        【解决方案4】:

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

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

        <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”。

        【讨论】:

        • 你也有错字“文本”
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-11
        • 2013-01-20
        • 2021-04-25
        • 2022-01-25
        • 1970-01-01
        • 1970-01-01
        • 2013-05-30
        相关资源
        最近更新 更多