fetch() 在 eventlistener on button 被激活之前被触发 - Chuck Norris AP



这很奇怪,我错过了什么。

我正在尝试让这个 API 在单击按钮时向我发送随机查克诺里斯报价。

但是,一旦我刷新页面,我就会得到一个新的报价。我只是想在我提交/单击按钮后为我提供新报价。

请参阅下面的 HMTL 和 JS:

<body>
<div>
<button id="xxx"> GET A CHUCK QUOTE</button>
<h1 id="chuck-quote"></h1>
</div>

<script>
const chuck_button = document.getElementById('xxx');
chuck_button.addEventListener('click', function () {
fetch('https://api.chucknorris.io/jokes/random') 
.then(response =>  {
return response.json();
}).then( data => {
const chuck_quote = document.getElementById('chuck-quote');
chuck_quote.innerHTML = JSON.stringify(data.value);
})
}());
</script>
</body>

删除行}());中的()。否则,将直接调用该函数。

您在设置时正在调用addEventListener函数,我删除了(),它工作正常。

const chuck_button = document.getElementById('xxx');
chuck_button.addEventListener('click', function() {
fetch('https://api.chucknorris.io/jokes/random')
.then(response => {
return response.json();
}).then(data => {
const chuck_quote = document.getElementById('chuck-quote');
chuck_quote.innerHTML = JSON.stringify(data.value);
})
});
<div>
<button id="xxx"> GET A CHUCK QUOTE</button>
<h1 id="chuck-quote"></h1>
</div>

相关内容

最新更新