外部JavaScript未运行,不写入文档
External JavaScript Not Running, does not write to document
我正试图使用外部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"。
相关文章:
- 从Javascript和Php变量创建Html模板文档
- 有没有一种方法可以在没有文档或jQuery的情况下使用javascript解码html实体
- 是否存在Javascript Liferay Service库的文档?如何处理错误情况
- 暂停文档-HTML、CSS、JavaScript
- 如何在外部文档中使用javascript将文本区域的内容保存为变量
- 将文档实体传递给JavaScript函数
- 如何用javascript重写html文档
- 将事件发送到javascript文档的react本机模块是否正确
- 加载的XML文档为null(Javascript)
- 用javascript从窗口获取文档,同时检查文档是否已加载
- Javascript em根据窗口/视口尺寸调整大小,不影响文档样式的text/css
- 创建自己的文档Javascript
- 你知道谷歌文档Javascript是如何进行间隔数据自动刷新的吗?
- MongoDB按日期范围查找文档-JavaScript
- ABCPdf添加文档javascript
- 如果在文档Javascript中找到URL,请替换该URL
- 我怎么能在循环中立即写入文档(javascript)
- 如何使用多个文档.JavaScript中的cookie
- 如何检测文档.javascript中的addEventListener支持
- 解析PDF文档javascript