javascript - 外部 JavaScript 函数未定义
问题描述
HTML 文件:
<html>
<body>
<main>
<div class="form-row">
<div class="form-group col-md-6">
<input type="email" class="form-control" id="inputEmail">
</div>
</div>
<button onclick="unsubscribe()" type="button">Unsubscribe</button>
</main>
<script src="js/unsubscribe.js" type="text/javascript"></script>
</body>
</html>
unsubscribe.js 内容:
function unsubscribe() {
var email=document.getElementById("inputEmail").value;
var requestOptions = {
method: 'POST',
redirect: 'follow'
};
fetch("https://apilink/"+email)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('Error!', error));
}
当我在外部 js 文件中定义函数并将 js 文件链接到 html 正文中时,我不确定为什么函数返回未定义。
解决方案
如果函数未定义,听起来不像是异步问题。听起来像一个相对路径问题。尝试:
<script src="/js/unsubscribe.js"></script>
(注意前导斜杠,表示从根目录开始查找 js 文件)。
推荐阅读
- html - Z-index 不适用于父(相对)子(绝对)元素
- snowflake-cloud-data-platform - 如何在雪花中获得最常执行的查询
- html - 将下拉菜单与父级对齐
- cmd - ERRORLEVEL 无法报告 regsvr32 的进程退出代码,为什么?
- arrays - 使用 ArrayAdapter 意味着不再使用循环?
- c++ - 我可以在 std::shared_mutex 上使用 std::shared_lock 更改数据吗?
- c++ - 何时释放函数中声明的堆栈分配变量?
- windows - Atom:包拼写检查无法加载 es-CL 的检查器
- mongodb - 从 mongodb 中的每个 x 文档的集合中获取所有文档
- c# - C#/WPF RSA 不解密文本