js中实现事件代理

var count = 10;

for(var i = count;i--;){

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

  div.innerHTML = "test_div"+i;

  div.className = "test_div";

  document.body.appendChild(div);

}

//绑定冒泡阶段点击事件

document.body.addEventListener('click', function(e){ 

  if(e.target && e.target.className == "test_div") {

    alert(e.target.innerHTML+' bubble');

  }

}, false)

//绑定捕获阶段点击事件

document.body.addEventListener('click', function(e){ 

  if(e.target && e.target.className == "test_div") {

    alert(e.target.innerHTML+' capture');

  }

}, true)

触发顺序:捕获阶段-》目标阶段-》冒泡阶段

原文地址:https://www.cnblogs.com/taojunlong/p/6833412.html