无法从外部JavaScript调用函数

时间:2018-04-22 17:45:07

标签: javascript html

我有一个简单的HTML页面,它调用JavaScript函数:

<!DOCTYPE html>
<html>
    <script type="text/javascript" src="css/myscript.js"></script>
    <head>
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body onload="javascript:hello()">
    </body>
</html>

这是我的hello()功能:

<script>
function hello() {
    alert("load new content");
    document.open();
    document.write("<h1>Changed content!</h1>");
    document.close();
}
</script>

直接将JavaScript块粘贴到页面中时,它可以正常工作。但是,如果JavaScript包含在专用文件中,则无法找到hello()

使用Developer工具,我可以看到JavaScript文件已成功加载。

3 个答案:

答案 0 :(得分:1)

如果你的js文件中有这些脚本标签,请删除它们。

答案 1 :(得分:1)

2个问题,在解析脚本期间,文档已经打开。如果再次打开,所有内容都将被删除,以便摆脱它(写入已经是打开的调用)。其次,确保在load事件之后不添加脚本,以便真正定义函数hello。在这里,我将其添加到正文中(或者如果您愿意,可以使用延迟。)Here is the fiddle

<head>
  <link rel="stylesheet" href="css/style.css">

</head>
<body onload="hello();">
</body>



 function hello() {
      alert("load new content");
      //document.open();
      document.write("<h1>Changed content!</h1>");
      document.close();
    }

答案 2 :(得分:1)

myscript.js的内容应该是:

function hello() {
  alert("load new content");
  document.open();
  document.write("<h1>Changed content!</h1>");
  document.close();
}

只有当您的JavaScript位于HTML文件中时,才会包含<script>标记; <script>告诉浏览器,“嘿,我们不再解释HTML。这是JavaScript。”

此外,正如Colin在评论中指出的那样,myscript.js可能不属于您的css文件夹。包含所有网站JavaScript文件的文件夹的通用名称为js