为什么我不能在侦听器函数中到达变量i?

时间:2019-05-21 23:21:06

标签: javascript

为什么我不能在侦听器函数中使用变量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);

1 个答案:

答案 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);