为什么我不能在侦听器函数中使用变量i?
const myCustomDiv = document.createElement('div');
for (let i = 1; i <= 200; i++) {
const newElement = document.createElement('p');
newElement.textContent = 'This is paragraph number ' + i;
newElement.addEventListener('click', function respondToTheClick(evt) {
console.log('A paragraph was clicked.'+i);
});
myCustomDiv.appendChild(newElement);
}
document.body.appendChild(myCustomDiv);
答案 0 :(得分:3)
对我有用,请检查您的问题是否正确。
const myCustomDiv = document.createElement('div');
for (let i = 1; i <= 200; i++) {
const newElement = document.createElement('p');
newElement.textContent = 'This is paragraph number ' + i;
newElement.addEventListener('click', function respondToTheClick(evt) {
console.log('A paragraph was clicked.'+i);
console.log(`the counter at this time was: ${i}`)
});
myCustomDiv.appendChild(newElement);
}
document.body.appendChild(myCustomDiv);