事件代理和闭包综合运用
使用场景:需要创建多个元素并绑定同类型事件
代码如下:
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Test</title>
</head>
<body>
<div id="div1">
<!-- 随时新增更多的 a 标签 -->
</div>
<script type="tetx/javascript">
let elem = document.getElementById('div1');
for (let i = 0; i < 10; i++) {
(function(i) {
let temp = document.createElement('a');
temp.innerHTML = i;
elem.appendChild(temp);
let temp2 = document.createElement('br');
elem.appendChild(temp2);
})(i);
}
elem.addEventListener('click', function(e) {
e.preventDefault();
if (e.target.nodeName === 'A')
console.log(e.target.innerHTML);
});
</script>
</body>
</html>