<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="box">
<p>段落1</p>
<p class="p1">段落2</p>
<h3>三级标题1</h3>
<h3 class="p1">三级标题2</h3>
<p>段落3</p>
<h3>三级标题3</h3>
<p class="p1">段落4</p>
<p>段落5</p>
<h3 class="p1">三级标题4</h3>
</div>
<p>123123</p>
</body>
<script>
var obox = document.querySelector(".box");
var ap = obox.getElementsByTagName("p");
// 一、封装:与this无关
// 事件要的是什么:函数
// 我们给的是什么:函数的执行结果
// 函数的执行结果是什么:返回值,默认是undefined
// 改变返回值成什么:函数
// 1.fn默认执行得到的是undefined
obox.onclick = fn(ap,function(t){
console.log(this)
})
function fn(child,callback){
// 2.修改fn的返回值为函数,作为将来真正的事件处理函数
return function(eve){
// 3.找事件对象身上的事件源
var e = eve || window.event;
var target = e.target || e.srcElement;
// 4.遍历传进来的要委托的子元素
for(var i=0;i<child.length;i++){
// 5.逐个与事件源的元素做比较,相同了表示找到了真正要触发的元素
if(child[i] === target){
// 二、this的改变
// 6.执行用户传进来的回调函数,完成用户指定的功能
// 的同时,修改this指向,为真正的事件源
callback.bind(target)()
}
}
}
}
</script>
</html>
长风破浪会有时,直挂云帆济沧海