我有一个 chrome 扩展的内容脚本,其中包含一个函数,该函数应该仅在单击特定按钮时触发。但我注意到,单击按钮时该函数会被触发一次,并且它会继续多次调用自身(不是无限的)
button.addEventListener("click", handleButtonClick);
function handleButtonClick() {
extractedData = function3();
// Your custom logic for button click
setTimeout(() => {
fillContentEditableWithDummyText('Loading...')
fetch('a valid end point',{
method: "POST",
body: JSON.stringify({
email: user.email,
extractedData: extractedData
})
}).then(res => res.json()).then(data => fillContentEditableWithDummyText(data.message))
},300);
//fillContentEditableWithDummyText();
}
当我尝试调试时,注意到一旦 function3() 返回,handleButtonClick() 函数就会再次被调用
button.addEventListener("click", handleButtonClick);
此行将在每次单击时向按钮添加一个新的单击事件。这意味着每次点击都会多次调用该函数。
您应该尝试使用 onclick。
button.onclick = handleButtonClick;