Javascript onclick不使用动态添加的按钮 问题

Javascript onclick不使用动态添加的按钮 问题,javascript,google-chrome-extension,Javascript,Google Chrome Extension,为具有动态添加按钮的单击事件添加事件处理程序不会在单击时产生任何结果。我正在尝试构建一个动态添加按钮的chrome扩展 代码 在内容脚本(js)中 当按钮确实被渲染时,单击按钮不会执行任何操作 笔记 不过,复选框的事件处理程序可以工作!使用href=“javascript:function()” 但是,当用户尚未单击任何内容时,只要网页已完全加载,对按钮执行相同操作,就会调用removestcky() 第一个代码是正确的,应该可以工作。事实上,这并不意味着有什么东西在干扰,例如,页面

为具有动态添加按钮的单击事件添加事件处理程序不会在单击时产生任何结果。我正在尝试构建一个动态添加按钮的chrome扩展

代码
  • 在内容脚本(js)中
  • 当按钮确实被渲染时,单击按钮不会执行任何操作
笔记
  • 不过,复选框的事件处理程序可以工作!使用
    href=“javascript:function()”

  • 但是,当用户尚未单击任何内容时,只要网页已完全加载,对按钮执行相同操作,就会调用
    removestcky()


第一个代码是正确的,应该可以工作。事实上,这并不意味着有什么东西在干扰,例如,页面可能有一个全局单击处理程序来停止事件的传播。在这种情况下,您可以尝试在addEventListener的第三个参数中指定
true
。尝试在添加按钮之前添加事件处理程序,尽管从您发布的内容来看它应该可以工作。
// 1. Create the button
        var button = document.createElement("button");
        button.innerHTML = "Do Something";

        // 2. Append somewhere in the document body
        var body = document.getElementsByTagName("body")[0];
        body.appendChild(button);

        // 3. Add event handler
        button.addEventListener ("click", function() {
          alert("did something");
        });
var check = document.createElement("input");
      check.id = "checkbox1";
      check.type = "checkbox";

        //if check is checked, then call removeSticky()
      check.href="javascript:removeSticky()"
      check.addEventListener('change', () => {
            if (check.checked) {
                removeSticky();
            } else {
                // nothing
            }
      });

      document.getElementById("sticky").append(check);


//hidesthe sticky note
function removeSticky() {
  window.alert("removeSticky() is working.");
  // Removes an element from the document.
  var element = document.getElementById("sticky");
  element.style.display = "none";
}