标签:git move focus blur lower === style use onload
答案:利用事件冒泡的原理,让自己的所触发的事件,让他的父元素代替执行!
解析:
1、那什么样的事件可以用事件委托,什么样的事件不可以用呢?
2、为什么要用事件委托
<ul>
<li>苹果</li>
<li>香蕉</li>
<li>凤梨</li>
</ul>
// good
document.querySelector(‘ul‘).onclick = (event) => {
let target = event.target
if (target.nodeName === ‘LI‘) {
console.log(target.innerHTML)
}
}
// bad
document.querySelectorAll(‘li‘).forEach((e) => {
e.onclick = function() {
console.log(this.innerHTML)
}
})
3、事件冒泡与事件委托的对比
4、事件委托怎么取索引?
<ul id="ul">
<li>aaaaaaaa</li>
<li>事件委托了 点击当前,如何获取 这个点击的下标</li>
<li>cccccccc</li>
</ul>
<script>
window.onload = function () {
var oUl = document.getElementById("ul");
var aLi = oUl.getElementsByTagName("li");
oUl.onclick = function (ev) {
var ev = ev || window.event;
var target = ev.target || ev.srcElement;
if (target.nodeName.toLowerCase() == "li") {
var that = target;
var index;
for (var i = 0; i < aLi.length; i++)
if (aLi[i] === target) index = i;
if (index >= 0) alert(‘我的下标是第‘ + index + ‘个‘);
target.style.background = "red";
}
}
}
</script>
拓展:
标签:git move focus blur lower === style use onload
原文地址:https://www.cnblogs.com/qiilee/p/14813098.html