javascript - 按钮上的 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
}
请帮忙。
解决方案
更新:
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>
推荐阅读
- python - Python datetime 简化 24 小时时间和总数据帧
- javascript - Typescript 和 Puppeteer 不允许我单击“document.querySelectorAll”中的元素
- jmeter - 使用 JMeter 记录流量而不使用 GUI
- c++ - 错误
使用 VSC2019 编译旧代码 - css - 用 url 覆盖除背景图片之外的所有背景图片
- python - 从文本文件创建列表
- javascript - 在 AJAX 中发送字符串参数
- javascript - 调用 firebase.auth 是否算作 Firebase 限制的下载?
- asp.net-core - 如何授权控制器 .NET Core API
- tensorflow - MNIST 识别手写单词