如何在Chrome扩展程序的弹出窗口中添加复选框的事件监听器?

Rom*_*man 15 javascript checkbox google-chrome-extension

我正在尝试捕获checkboxChrome扩展程序弹出窗口中的更改.文件:

内联JavaScript将不会被执行

在同一页面上提供了一个示例,但它用于button.我不知道如何修改它以便捕获chekbox的状态变化.

document.addEventListener('DOMContentLoaded', function () {
      document.querySelector('button').addEventListener('click', clickHandler);
});
Run Code Online (Sandbox Code Playgroud)

例

Ric*_*eau 26

有同样的问题,但引用一个非常有用的网站,在Javascript中列出事件.在对关键字"check"进行快速搜索(Ctrl + F)后,我发现列出了"更改"事件...据说与大多数浏览器兼容.当然,它确实存在,所以我的假设是,复选框可能存在"更改事件".低,看看它只是测试它似乎工作.这是你的代码修改了一点和事件的链接(http://help.dottoro.com/larrqqck.php):

popup.html中的html示例

    <div class="menu" >
<input type="checkbox" id="showAlert" name="showAlert"/>
<label for="showAlert"><nobr>Show Alert</nobr></label></div>
Run Code Online (Sandbox Code Playgroud)

popup.js中的代码片段示例

document.addEventListener('DOMContentLoaded', function () {
      document.querySelector('#showAlert').addEventListener('change', changeHandler);
});
Run Code Online (Sandbox Code Playgroud)

当然,您需要将其传递给以下函数:

function changeHandler(){
   //Do Something...maybe another function showAlert(), for instance
   if(showAlert.checked){
      //do something
   }
   else{
      //do something else
   }
}
Run Code Online (Sandbox Code Playgroud)

01/06/2018 - 编辑: 我只是回头看看这篇文章,看来这可能会被弃用.因此,您可能希望使用MutationObserver(https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver).

  • 我可能会使用这个changeHandler:`function changeHandler(e){if(e.target.checked){alert("Checked"); } else {alert("未选中"); } (3认同)