javascript - 使用 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 不是它所期望的。
解决方案
每当你点击你的 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 文档
推荐阅读
- r - R中分组数据的条件格式
- javascript - JSLint “这个函数需要一个‘use strict’ pragma。”
- html - 过滤 url 之间的所有内容
- google-cloud-platform - Google Cloud Datastore:使用 Node.js 批量导入
- android - 使用 .so 和 .com 文件打包到 .aar 库中
- powershell - 如何延迟 IIS 重启服务器?
- mongodb - Mongo:创建唯一的文本索引
- java - 使用 selenium webdriver 和 java 在 testng 中的数据提供者
- go - 如何使用连接池连接到 aerospike 服务器
- asp.net-core - AspNetCore Api 路由中的 Base64 编码