javascript - 具有 SetInterval 方法的按钮上的单击事件
问题描述
我无法弄清楚如何实现这一点。我正在研究 chrome 扩展,我有一个 setInterval 方法,它监视页面上的按钮,当它被点击时,它运行一个函数。但问题是,当我单击按钮时,该函数运行多次,我清楚地理解这是因为 Interval 函数,但我希望 setInterval 始终在此页面上运行,以便我可以监视按钮是否被单击或不是。下面是我的代码
$(function(){
var url=window.location.href;
findAction(url);
}
function findAction(url){
setInterval(()=>{
Acceptbtn = $("[slot=primary-content-area")[4].querySelector("sn-inbox");
if(Acceptbtn !== undefined && Acceptbtn !== null){
Acceptbtn.addEventListener('click', myFunction);
}
function myFunction() {
console.log("clicked");
runAction(url)
};
},1000);
}
有什么办法可以解决这种情况,或者我做了一些简单的、复杂的事情还是我的方法完全错误。?
Interval 方法不断检查此按钮,一旦找到并单击它,我希望执行 runAction(url) 函数。使用我当前的代码,该函数被执行但多次
解决方案
只添加一次事件监听器
sn-inbox
如果是一个类并且[slot=primary-content-area]
缺少一个类,则选择器也不正确]
我在这里委托 - 如果您委托给最近的静态容器(这里是文档,因为我不知道在您的情况下最近的容器),您总是可以在按钮存在时找到它:
const url = window.location.href;
$(document).on("click", "[slot=primary-content-area]", function() {
if ($(this).index() === 3) { // 0 based - so the 4th slot
const $inbox = $(this).find(".sn-inbox");
if ($inbox.length > 0) {
$inbox.html("running");
runAction(url)
}
}
})
执行函数的示例代码:
https://jsfiddle.net/mplungjan/p93cj0Le/
$(function() {
const runAction = url => console.log("running", url);
const url = window.location.href;
$(document).on("click", "[slot=primary-content-area]", function() {
if ($(this).index() === 3) { // 0 based
const $inbox = $(this).find(".sn-inbox");
if ($inbox.length > 0) {
$inbox.html("running");
runAction(url)
}
}
})
// testing the code
setInterval(() => {
$("#container").html(`<div>
<div slot="primary-content-area"></div>
<div slot="primary-content-area"></div>
<div slot="primary-content-area"></div>
<div slot="primary-content-area"><button class="sn-inbox">Click</button></div>
</div>`)
}, 5000)
setTimeout(() => $("#container").html(""), 2000)
})
<div id="container">
</div>
推荐阅读
- javascript - 如何在javascript中将方法导入Worker Scope?
- r - 根据另一个参考表在数据框中的一列中插入值
- django - 使用for循环在django中动态访问表字段
- ios - 在 React Native 0.62 更新后找不到 -lBranch 的库
- algorithm - 将一棵二叉搜索树右转换为另一棵的时间复杂度
- javascript - Onkeyup javascript错误计算变化
- reactjs - React 功能组件在某些条件下从上下文调用其他函数或调用方法
- flutter - 根据存储在共享首选项中的记住我状态导航到屏幕
- reactjs - 使用 @ 访问 react native 中的一些文件夹
- javascript - 带有自动完成 jqueryui 的 UIKIT 3 模态