英文:
Why after adding elements to the document the addEventListener stop working?
问题
在你的代码中有两个 .addEventListener
,但其中一个在向 <body>
添加一个 <div>
后停止工作。
document.addEventListener("mousemove", (e) => { mouseMove(e) }, false);
document.body.addEventListener("click", function(e){
e = e || window.event;
if (e.which == 1) fire();
}, false);
function fire(){
let bullet = `<div class="bullet" style="left:${shooterPlace.x}px;top:${shooterPlace.y}px;"></div>`;
document.getElementById("space").innerHTML += bullet;
}
在点击后,我制作的枪停止旋转,这是因为事件监听器停止了。
HTML:
<div class="body-copier" id="space">
<div id="gun">
<div id="gun-shooter-place"></div>
</div>
</div>
英文:
I have two .addEvenetListener in my code but one of them stop working after adding a div to my <body>
document.addEventListener("mousemove", (e) => { mouseMove(e) }, false);
document.body.addEventListener("click", function(e){
e = e || window.event;
if (e.which == 1) fire();
}, false);
function fire(){
let bullet = `<div class="bullet" style="left:${shooterPlace.x}px;top:${shooterPlace.y}px;"></div>`;
document.getElementById("space").innerHTML += bullet;
}
After clicking, the GUN that I made stops rotating due to the stop of the eventlistener
HTML:
<div class="body-copier" id="space">
<div id="gun">
<div id="gun-shooter-place"></div>
</div>
</div>
答案1
得分: 0
尝试这个:
let bullet = document.createElement("div");
Object.assign(bullet, { class: "bullet", style: `left:${shooterPlace.x}px;top:${shooterPlace.y}px;` });
document.getElementById("space").append(bullet);
您的 .space 元素被编辑出了 DOM,因此它失去了它的事件监听器,因为您的 innerHtml += "something new" 相当于 .innerHtml = "something berfore with something new"。
您想要向 DOM 添加额外的元素,但 .innerHtml 不会实现这一点。
无论如何,您没有提供可复制的代码(缺少 HTML),所以我不知道您的枪元素在哪里(我假设它在 .space 元素内部)。
英文:
Try this
let bullet = document.createElement("div");
Object.assign(bullet,{class:"bullet",style:`left:${shooterPlace.x}px;top:${shooterPlace.y}px;`});
document.getElementById("space").append(bullet);
Your .space element is edited out of DOM, so it loses it's eventListeners as Your innerHtml+="something new" is the same as .innerHtml="something berfore with something new" .
You want to add additional element to DOm but .innerHtml doesn't do this.
Anyway You didn't provide reproducable code (html missing) so i don't know where is Your gun element (i suppose it's inside .space element)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论