首页 > 解决方案 > 使用 appendChild(iDiv) 向 div 元素添加点击事件时获取错误参数

问题描述

我正在尝试使用 appendChild(iDiv) 将点击事件添加到 div 元素,但我得到了错误的参数。

这是我的代码:

function showHand() {
    fetch('http://127.0.0.1:5000/showHandPlayer1')
        .then(response => response.json())
        .then(data => {
            for (z = 0; z < data.length; z++) {
                console.log(z);
                var iDiv = document.createElement('div');
                iDiv.id = 'card'+z;
                iDiv.innerHTML = data[z] + ' - ' + z;
                iDiv.addEventListener('click', function() {playCard(z)}, false); 
                document.getElementById('hand').appendChild(iDiv);
            }
        });
}
function playCard(i) {
    fetch('http://127.0.0.1:5000/playCard/'+i)
        .then(response => response.text())
        .then(data => {
        console.log(data + " is played.");
    });

fetch 正在返回一个列表 [ "Yellow0", "Red5", "RedDirection", "ChangeCollor" ]

这是检查器中的结果:

在此处输入图像描述

在控制台中,我收到此错误:

TypeError: NetworkError when attempting to fetch resource.

TypeError: x is null
uno.html:22:4
Forespørgsel til fremmed websted blokeret: Politikken for samme oprindelse tillader ikke læsning af fjernressourcen http://127.0.0.1:5000/playCard/4. (Årsag: CORS-headeren 'Access-Control-Allow-    Origin' findes ikke).

单击它们时,我在所有 4 个 div 中都遇到相同的错误。它指的是http://127.0.0.1:5000/playCard/4,而我列表中只有 0,1,2,3 。为什么会这样以及如何使 clickevent 看起来像这样: onclick="playCard(0)", onclick="playCard(1)", onclick="playCard(2)",onclick="playCard(3)"

后端服务器通过“IndexError: list index out of range”,因为 4 不是它所期望的。

标签: javascriptfetchappendchild

解决方案


每当你点击你的 div 的值将z是你的 for 循环的最后一个值。为了防止这种情况,您需要将这些行包装在一个闭包中。

for (let z = 0; z < data.length; z++) {
    (function(index) {
        console.log(index);
        var iDiv = document.createElement('div');
        iDiv.id = 'card'+index;
        iDiv.innerHTML = data[index] + ' - ' + index;
        iDiv.addEventListener('click', function() {playCard(index)}, false); 
        document.getElementById('hand').appendChild(iDiv);
    })(z) 
}

有关闭包的更多信息,请查看mdn 文档


推荐阅读