【javascript】循环中设置的监听事件怎么传递参数

循环中设置的监听事件怎么传递参数

for(var m = 0; m < detialList.length; m++) {

  var itemDetial = document.createElement('div');

     itemDetial.onclick=function(){

    alert(detialList[m].data); 

  }

}

只能弹出m最大值时候的值

解决办法:“闭包”

for(var m = 0; m < detialList.length; m++) {

  var itemDetial = document.createElement('div');

        var paraTrans = function (data) {

   itemDetial.onclick=function(){

     alert(data); 

   }

   };
  paraTrans(detialList[m].data);

}
原文地址:https://www.cnblogs.com/hanjunjun/p/8296354.html