JS事件委托和事件分派
JS事件委托
定义:若需要对子元素进行统一的监听管理,可以将其委托给它们共同的父元素,通过event对象对指定子元素进行筛选和操作。
<body>
<ul class="wrap">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
let oWrap = document.querySelector(".wrap")
oWrap.addEventListener("click", function (e) {
if (e.target.tagName.toLowerCase() === "li") {
console.log(e.target.innerText);
}
},false)
</script>
</body>
当点击每个li时,获取文本内容
 
JS事件分派
定义:对于同一组或一类相关联事件,可以对其中各部分回调函数进行统一分派映射管理
<body>
<div class="wrap">1</div>
<script>
let oWrap = document.querySelector(".wrap")
let assignObj = {
mousedown: function (e) {
console.log("我是mousedown");
},
mousemove: function (e) {
console.log("我是mousemove");
},
mouseup: function (e) {
console.log("我是mouseup");
},
}
oWrap.addEventListener("mousedown", assignTask, false)
oWrap.addEventListener("mousemove", assignTask, false)
oWrap.addEventListener("mouseup", assignTask, false)
function assignTask(e) {
if (assignObj[e.type] && typeof assignObj[e.type] === "function") {
assignObj[e.type]()
}
}
</script>
</body>
成功触发分派事件
 
|