简体   繁体   English

无法从外部JavaScript调用函数

[英]Unable to call function from external JavaScript

I have a simple HTML page which calls a JavaScript function: 我有一个简单的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>

This is my hello() function: 这是我的hello()函数:

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

When pasting the JavaScript block into the page directly, it works. 将JavaScript块直接粘贴到页面中时,它可以工作。 However it's not able to find hello() if the JavaScript is contained within a dedicated file. 但是,如果JavaScript包含在专用文件中,则无法找到hello()

Using the Developer tools I can see that the JavaScript file is loaded successfully. 使用开发人员工具,我可以看到JavaScript文件已成功加载。

如果您的js文件中包含这些脚本标签,请摆脱它们。

2 issues, during parsing of your script, document is already open. 2个问题,在脚本解析期间,文档已经打开。 If you open again, everything will be deleted so get rid of it(write is already a call to open). 如果再次打开,所有内容都将被删除,因此将其删除(write已经是打开的调用)。 Second, make sure you do not add the script after the load event, so that function hello is really defined. 其次,请确保不要在load事件之后添加脚本,以便真正定义函数hello。 Here I am adding it right within body (or you can use defer if you want.) Here is the fiddle 在这里,我将其添加到正文中(或者如果需要,可以使用defer。) 这是小提琴

<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();
    }

The contents of myscript.js should just be: myscript.js的内容应为:

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

You would include the <script> tag only if your JavaScript were inside your HTML file; 仅当您的JavaScript位于HTML文件中时,才包括<script>标记。 the <script> is what tells the browser, "Hey, we're not interpreting HTML anymore. This is JavaScript." <script>告诉浏览器,“嘿,我们不再解释HTML。这是JavaScript。”

Also, as Colin pointed out in the comments, myscript.js probably doesn't belong in your css folder. 而且,正如Colin在评论中指出的那样, myscript.js可能不属于您的css文件夹。 A common name for the folder that contains all your website's JavaScript files is js . 包含您网站的所有JavaScript文件的文件夹的通用名称是js

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

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