我创建了这个片段:
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
}请帮帮忙。
发布于 2021-03-01 19:50:39
最新情况:
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中,为什么不只是在使用目标元素或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>
https://stackoverflow.com/questions/66425590
复制相似问题