首页 > 解决方案 > 具有 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);

} 

有什么办法可以解决这种情况,或者我做了一些简单的、复杂的事情还是我的方法完全错误。?

下面是我的扩展程序监视接受按钮的 Div - 在此处输入图像描述

一旦单击接受按钮,就会发生这种情况 在此处输入图像描述

Interval 方法不断检查此按钮,一旦找到并单击它,我希望执行 runAction(url) 函数。使用我当前的代码,该函数被执行但多次

标签: javascriptjquerygoogle-chrome-extension

解决方案


只添加一次事件监听器

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>


推荐阅读