为什么在向文档添加元素后,addEventListener 不再起作用?

huangapple go评论75阅读模式
英文:

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(&quot;mousemove&quot;, (e) =&gt; { mouseMove(e) }, false);
document.body.addEventListener(&quot;click&quot;, function(e){
    e = e || window.event;  
    if (e.which == 1) fire();
}, false);

function fire(){
    let bullet = `&lt;div class=&quot;bullet&quot; style=&quot;left:${shooterPlace.x}px;top:${shooterPlace.y}px;&quot;&gt;&lt;/div&gt;`;
    document.getElementById(&quot;space&quot;).innerHTML += bullet;
}

After clicking, the GUN that I made stops rotating due to the stop of the eventlistener

HTML:


    &lt;div class=&quot;body-copier&quot; id=&quot;space&quot;&gt;
        &lt;div id=&quot;gun&quot;&gt;
            &lt;div id=&quot;gun-shooter-place&quot;&gt;&lt;/div&gt;
        &lt;/div&gt;  
    &lt;/div&gt;

答案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(&quot;div&quot;);
 Object.assign(bullet,{class:&quot;bullet&quot;,style:`left:${shooterPlace.x}px;top:${shooterPlace.y}px;`});

document.getElementById(&quot;space&quot;).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)

huangapple
  • 本文由 发表于 2023年2月18日 20:01:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75493198.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定