如何从外部链接JS文件

How to link a JS file externally?

本文关键字:JS 文件 链接 从外部      更新时间:2024-04-28

我遇到了这个问题。所需的条件是外部文件不应包含脚本标记。但是,为了调用函数,需要使用script标记。代码只是一个例子。此外,还有任何其他选项可以链接外部JS文件。

<!DOCTYPE html>
<html>
<body>
<script src="Friendship.js">
</script>
</body>
</html>

外部JS的代码是:

<!DOCTYPE html>
<head>
<script>
function mySpace()
{
document.getElementById("playa").innerHTML="Friendship is always a sweet responsibility, never an opportunity.
";
}
</script>
<body>
<h1><tt>Friendship</tt></h1>
<p id="playa">"One of the most beautiful qualities of true friendship is to understand and to be understood.
"</p>
<button type="button" onclick="mySpace()">Click Here !</button>
</body>
</html>

一个Javascript文件,应该只包含Javascript代码。它不应该包含HTML、CSS或任何其他标记。

根据上面的例子,您应该有以下两个文件:

index.html

<!DOCTYPE html>
<html>
<body>
    <!-- Link to external JavaScript file -->
    <script src="friendship.js"></script>
    <h1><tt>Friendship</tt></h1>
    <p id="playa">"One of the most beautiful qualities of true friendship is to understand and to be understood."</p>
    <button type="button" onclick="mySpace()">Click Here !</button>
</body>
</html>

交友.js

// This is a comment
function mySpace()
{
    document.getElementById("playa").innerHTML="Friendship is always a sweet responsibility, never an opportunity.";
}

备注

friendship.js是纯JavaScript(或者上面的例子中的注释)。您不应该向JavaScript文件中添加任何HTML标记,如<html><body>等。您也不需要包含会产生错误的<script>标记。

可以在没有HTML声明的情况下编写JS代码吗

我不太清楚你说的是什么意思,但我会尽力解释的。如果您访问http://www.example.com/friendship.js,则会看到该文件中的原始JavaScript代码。该代码不会自动执行。您需要从HTML文件本身启动JavaScript,就像您在使用onclick="mySpace()"的HTML中所做的那样。