用JS创建10个<a>标签,点击的时候弹出来对应的序号

利用闭包的方式

for (var i = 0; i < 10; i++) {
  var aObj = document.createElement('a')
  aObj.innerText = 'a标签' + i
  aObj.onclick = (function (i) {
    return function () {
      alert(i)
    }
  })(i)
  document.body.appendChild(aObj)
}

利用块级作用域的方式

for (let i = 0; i < 10; i++) {
  let aObj = document.createElement('a')
  aObj.innerText = 'a标签' + i
  aObj.onclick = function () {
    alert(i)
  }
  document.body.appendChild(aObj)
}

 

posted @ 2020-12-23 14:41  hiuman  阅读(167)  评论(0编辑  收藏  举报