动态创建的HTML元素不与事件监听器配合工作。

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

Dynamically created HTML elements don't work with event listeners

问题

简而言之,我想实现在我的象棋游戏中拖放功能(就像你可以拖动棋子)。但是出现了一些问题。

问题:
动态创建的棋子(右侧的棋子)在其属性列表中具有所需的事件侦听器,因为我首先动态创建它,然后再为每个棋子添加事件侦听器。但它不起作用。例如,我放置另一个在HTML中创建的棋子(左侧的棋子),一切都正常。

问题预览(图片)

HTML:

<body>
    <div id="chess_field">
        <button class="place" id="place11">
            <div class="figure wp" id="" draggable="true"></div>
        </button>
        ...
    </div>
    <script defer src="scripts_ui.js"></script>
</body>

JavaScript:

let chessField = [[0, 0, 0, "wp", 0, 0, 0, 0]];

let dragged_element;

function DragEventAdd() {
    let figure = window.document.querySelectorAll(".figure");
    ...
}

function arrangeFigures() {
    ...
}

let place_drop = window.document.querySelectorAll(".place");
    ...
arrangeFigures();

CSS:

...

代码描述:
变量 "chessField" 是一个包含有关棋子位置信息的二维数组。

"arrangeFigures" 函数 - 负责将棋子添加到具有 "place" 类的单元格中。

"DragEventAdd" 函数 - 为它们添加事件侦听器。

英文:

In short, I wanted to implement drag and drop in my chess (like you can drag chess pieces). But something is wrong.

Problem:
The dynamically created chess piece (the one to the right) has the required event listener in its property lists, since I first dynamically create it, and only then add an event listener to each. But it doesn't work. For example, I put another chess piece (the one on the left) created in html. And everything works on it.

Problem preview (img)

HTML:

&lt;body&gt;
    &lt;div id=&quot;chess_field&quot;&gt;
        &lt;button class=&quot;place&quot; id=&quot;place11&quot;&gt;
            &lt;div class=&quot;figure wp&quot; id=&quot;&quot; draggable=&quot;true&quot;&gt;&lt;/div&gt;
        &lt;/button&gt;
        &lt;button class=&quot;place&quot; id=&quot;place12&quot;&gt;
        &lt;/button&gt;
        &lt;button class=&quot;place&quot; id=&quot;place13&quot;&gt;
        &lt;/button&gt;
        &lt;button class=&quot;place&quot; id=&quot;place14&quot;&gt;
        &lt;/button&gt;
        &lt;button class=&quot;place&quot; id=&quot;place15&quot;&gt;
        &lt;/button&gt;
        &lt;button class=&quot;place&quot; id=&quot;place16&quot;&gt;
        &lt;/button&gt;
        &lt;button class=&quot;place&quot; id=&quot;place17&quot;&gt;
        &lt;/button&gt;
        &lt;button class=&quot;place&quot; id=&quot;place18&quot;&gt;
        &lt;/button&gt;
    &lt;/div&gt;
    &lt;script defer src=&quot;scripts_ui.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;

JavsScript:

let chessField = [[0, 0, 0, &quot;wp&quot;, 0, 0, 0, 0]];

let dragged_element;

function DragEventAdd() {
    let figure = window.document.querySelectorAll(&quot;.figure&quot;);
    figure = Array.from(figure);
    figure.map((f) =&gt; {
        f.addEventListener(&#39;dragstart&#39;, (event) =&gt; {
            console.log(&quot;drag started&quot;);
        });
    });
}

function arrangeFigures() {
    chessField.map((i, y) =&gt; {i.map((j, x) =&gt; {
            if (j !== 0) {
                let place = window.document.getElementById(`place${y+1}${x+1}`);
                let figure = document.createElement(&quot;div&quot;);
                figure.classList.add(&quot;figure&quot;);
                figure.classList.add(j);
                figure.setAttribute(&quot;graggable&quot;, true);
                place.appendChild(figure);
            }
        })});
        debugger;
    DragEventAdd();
}

let place_drop = window.document.querySelectorAll(&quot;.place&quot;);
    place_drop = Array.from(place_drop);
    place_drop.map((pd) =&gt; {
        pd.addEventListener(&#39;drop&#39;, (event) =&gt; {
            dragged_element = &quot;&quot;;
        });
    });
arrangeFigures();

CSS:

body {
  width: 100vw;
  height: 100vh;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#chess_field {
  width: 80vh;
  height: 80vh;

  display: flex;
  flex-wrap: wrap;
}

.place {
  width: 10vh;
  height: 10vh;
}

.figure {
  width: 100%;
  height: 100%;
  background-size: contain;
  background-color: aqua;
}

.wp {
  background-image: url(img/wp.png);
}

Code description:
The variable "chessField" is a two-dimensional array containing information about where the chess pieces are.

"arrageFigures" function - deals with adding chess pieces to cells with "place" classes.

Function "DragEventAdd" - ADDS EVENT LISTENERS TO THEM.

I rummaged through the entire StackOverflow, and all the problems associated with this were caused by the fact that people did not give event listeners to newly created elements. But that doesn't seem to be the problem.

答案1

得分: -1

以下是您要翻译的内容:

function arrangeFigures() {
    chessField.map((i, y) => {
        i.map((j, x) => {
            if (j !== 0) {
                let place = window.document.getElementById(`place${y+1}${x+1}`);
                let figure = document.createElement("div");
                figure.classList.add("figure");
                figure.classList.add(j);
                figure.setAttribute("draggable", true);
                place.appendChild(figure);
            }
        });
    });

    DragEventAdd();
}
英文:

Quick fix

function arrangeFigures() {
    chessField.map((i, y) =&gt; {
        i.map((j, x) =&gt; {
            if (j !== 0) {
                let place = window.document.getElementById(`place${y+1}${x+1}`);
                let figure = document.createElement(&quot;div&quot;);
                figure.classList.add(&quot;figure&quot;);
                figure.classList.add(j);
                figure.setAttribute(&quot;draggable&quot;, true);
                place.appendChild(figure);
            }
        });
    });

    DragEventAdd();
}

huangapple
  • 本文由 发表于 2023年5月7日 00:22:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76189950.html
匿名

发表评论

匿名网友

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

确定