Javascript fetch() 函数在点击时不起作用



我有一个简单的代码,当我点击按钮时,它会要求程序使用fetch((来获取一些数据:

<button id="hello-btn">Say Hello!</button>
<script>
var route = "/a-url";
let fetch_data = (route) => {
fetch(route)
.then(res => res.text())
.then(data => $("#resp").text(data))
}

$("#hello-btn").click((route) => {
fetch_data(route);
});
</script>

当我单击该按钮时,fetch_data((将不会运行。当我在.click((函数之外运行fetch_data((时,它运行得很好。

有什么解释吗?非常感谢。

问题是,在#hello-btn-click函数中,您将route定义为click事件对象,并将其作为函数中使用的路由变量。

请尝试使用所需的URL调用函数。

let fetch_data = (route) => {
fetch(route)
.then(res => res.text())
.then(data => $("#resp").text(data))
}
$("#hello-btn").click((e) => {
fetch_data("/a-url");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="hello-btn">Say Hello!</button>

最新更新