从脚本标签内调用外部 js 文件中的 js 函数

时间:2021-07-14 04:51:52

标签: javascript html script-tag external-js

我有一个带有脚本标签的 HTML 文件。为了复用其他页面通用的功能,我创建了一个带有一些功能的外部JS文件。现在,如果我在头部链接外部 JS 文件并尝试使用 onclick="functionname()" 访问作为 HTML 标记属性的函数,它会起作用。但是我想在脚本标签内调用外部 JS 文件中的函数(我需要将参数传递给函数并在脚本标签中提取这些值),我无法这样做。甚至可以在脚本标签内调用外部文件中的函数吗?如果是,如何做到这一点?

1 个答案:

答案 0 :(得分:1)

  1. 创建js文件。例如。 index.js
  2. 使用 script 标签在 HTML 文件中添加 index.js 文件
  3. 在您的 html 中添加 onClick="functionName()"

确保您使用的函数必须存在于 index.js 文件中

检查下面的代码

<body>
<script type="text/javascript" src="index.js"></script>
<script type="text/javascript">
    function call() {
        showAlert()
    }
</script>

<button onclick="call()">Call External Function</button>
</body>

首先加载外部js文件如下

<script type="text/javascript" src="index.js"></script>

添加新的脚本标签并添加另一个函数来调用外部函数

<script type="text/javascript">
function callExternalFun() {
    showAlert()
}
</script>

然后在 HTML 中添加 callExternalFun()

<button onclick="callExternalFun()">Call External Function</button>

包含index.js函数的外部JS代码showAlert

function showAlert() {
  alert("External JS Function")
}
相关问题