首页 > 解决方案 > 外部 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 正文中时,我不确定为什么函数返回未定义。

标签: javascripthtml

解决方案


如果函数未定义,听起来不像是异步问题。听起来像一个相对路径问题。尝试:

<script src="/js/unsubscribe.js"></script>

(注意前导斜杠,表示从根目录开始查找 js 文件)。


推荐阅读