gpt4 book ai didi

javascript - 对于每个不适用于通过单击创建的元素

转载 作者:行者123 更新时间:2023-12-02 23:18:22 24 4
gpt4 key购买 nike

我想要的:每当我点击任何“你好”世界时,它应该提醒我你好,即使在这些“你好”上,它们也是由按钮创建的

这是我尝试过 For(of)ForEach() 但没有任何效果的代码

这是我的尝试

let btn = document.getElementById("kick");
btn.onclick = function() {
let NewP = document.createElement("p");
let createText = document.createTextNode("Hello");
NewP.appendChild(createText);
NewP.classList.add("hello");
document.body.appendChild(NewP);
}
let allClasshello = document.getElementsByClassName("hello");
let allClasshelloAr = Array.from(allClasshello);
allClasshelloAr.forEach(function popup(elemetnWithHello) {
elemetnWithHello.onclick = function() {
window.alert("Hello")
}
})
<p class="hello">Hello</p>
<button id="kick">Create ME</button>

Javascript 新功能

最佳答案

forEach 仅在此代码的开头、用户添加任何元素之前被调用,因此 onclick 事件仅添加到第一个元素。您需要为每个新添加的元素添加 onclick 函数:

btn.onclick = function(){
let NewP = document.createElement("p");

...

NewP.onclick = function(){
window.alert("Hello")
}
}

关于javascript - 对于每个不适用于通过单击创建的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57062042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com