HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="box">box1</div>
<div class="box">box2</div>
<div class="box">box3</div>
<div class="hello">hello</div>
</div>
<button id="add">add</button>
</body>
</html>
JavaScript
function $(selector){
return document.querySelector(selector);
}
function $$(selector){
return document.querySelectorAll(selector);
}
$$('.box').forEach(function(node){
node.onclick = function(){
console.log(this.innerText);
}
})
// $$('.box').forEarch(function(node){
// node.onclick = function(){
// console.log(this.innerText);
// }
// })
//onclick只能绑定单个事件,若要绑定多个事件,则需使用forEarch循环遍历每个元素都绑定一个事件。
$('.container').onclick = function(e){
if(e.target.classList.contains('box')){
console.log(e.target.innerText);
}
}
//单点击按钮时候在container下再增加一个box。
var i = 4
$('#add').onclick = function(){
var box = document.createElement('div');
box.classList.add('box');
box.innerText = 'box' + (i++);
$('.container').appendChild(box);
};
将事件绑定在元素的父元素上,不用遍历上面的元素更加方便。事件冒泡总会冒泡到这个container上,对于后期新增的一些元素使用事件代理的效果更好些。
image.png











网友评论