首页 > 解决方案 > 按钮上的 TamperMonkey EventListener 不起作用

问题描述

我创建了这个片段:

function addClick(button, container) {
    console.log("In add click");
    const data = container.nextElementSibling.childNodes[0].innerHTML;
    button.addEventListener('click', ()=>{
        alert('clicked')
        console.log("Clicked");
    })
}

function createCopyButtons(array){
    array.forEach(element => {

        const container = document.createElement('div');
        const button = document.createElement('button');

        button.innerHTML = "Copy"
        
        styleContainer(container);
        styleButton(button, element);
        stylePrevious(element);
        
        container.innerHTML = element.outerHTML + button.outerHTML;

        element.parentNode.replaceChild(container, element);

        addClick(button, container); 

    });
}

现在在这里,数组是我希望应用此属性的 DOM 元素数组,我调用 createCopyButtons() 函数并添加更多内容。现在的问题是这个事件监听器不适用或不起作用。我试图等到这些答案加载了文档,然后才应用我的 javascript 片段,但事件侦听器似乎不起作用。

document.addEventListener("DOMContentLoaded", function(event) { 
  //do work
});

if (document.readyState == "complete") {
     // document is ready. Do your stuff here
   }

请帮忙。

标签: javascriptdomevent-listenertampermonkey

解决方案


更新:

function addClick(button) {
    button.addEventListener('click', ()=>{
        console.log("Clicked");
    })
}

let p = document.querySelectorAll('p');

// innerHTML not work
let btn1 = document.createElement('button');
btn1.innerHTML = "Not work";
p[0].innerHTML = btn1.outerHTML;
addClick(btn1)

// work
let btn2 = document.createElement('button');
btn2.innerHTML = "work";
p[1].appendChild(btn2);
addClick(btn2)
<p></p>
<p></p>


(.innerHTML)因为您使用字符串而不是 DOM 或使用将按钮附加到容器appendChild()

container.innerHTML = element.outerHTML + button.outerHTML

以下函数将不应用该事件

addClick(button, container);

我不知道为什么你需要将目标元素和按钮包装在里面div,为什么不直接在目标元素之后使用 or 附加按钮,insertBefore()insertAdjacentHTML()下面是你的工作代码。

它找到内部的按钮container用作addClick()参数

function addClick(button, container) {
  console.log("In add click");
  const data = container.nextElementSibling.childNodes[0].innerHTML;

  button.addEventListener('click', () => {
    alert('clicked')
    console.log("Clicked");
  })
}

function createCopyButtons(array) {
  array.forEach(element => {

    const container = document.createElement('div');
    let button = document.createElement('button');

    button.innerHTML = "Copy"

    container.innerHTML = element.outerHTML + button.outerHTML;

    element.parentNode.replaceChild(container, element);

    let btn = container.querySelector('button'); // <== find the button
    addClick(btn, btn.parentNode);

  });
}
createCopyButtons(document.querySelectorAll('input'))
<div>
  <input type="text">
  <p><span>test</span></p>
</div>


推荐阅读