一、 事件冒泡
当我们点击子元素触发父元素的事件,这种现象,我们叫做事件冒泡,即由子元素向祖先元素传播,就像气泡从水底上浮
阻止事件冒泡传递 死记
event.stopPropagation();!
<style>
*{
padding:0;
margin:0;
}
.box1{
width: 300px;
height: 300px;
background-color: orange;
}
.box2{
width: 100px;
height: 100px;
background-color: red
}
</style>
</head>
<body>
<div class="box">
<div class="box1">
<div class="box2"></div>
</div>
</div>
<script>
var box1 = document.querySelector(".box1");
var box2 = document.querySelector(".box2");
var box = document.querySelector(".box");
box1.onclick = function (){
console.log("我是box1");
}
box2.onclick = function (event){
event.stopPropagation();//阻止事件冒泡传递 死记!
console.log("我是box2");
}
box.onclick = function (){
console.log("我是box");
}
</script>
</body>
二、事件委托
通俗的讲,子代有事,让父级执行,当我们点击li时,子元素会通过事件的冒泡来触发父元素的事件,主要是通过事件冒泡
事件委托的原理
:不要给每个子节点单独设置事件监听器,而是事件监听设置在其父节点上,然后利用冒泡原理影响设置每个子节点
注意:此处使用了target来获取标签内容
<style>
li{
list-style: none;
height: 50px;
line-height: 50px;
background-color: orange;
}
</style>
</head>
<body>
<ul>
<li>
<span>我是span1</span>
<button>删除</button>
</li>
<li>
<span>我是span2</span>
<button>删除</button>
</li>
</ul>
<script>
// 需求,点击button之后删除整行
// for循环给每个button按钮添加点击事件
var ul = document.querySelector('ul');
//找到共同的父级
ul.onclick = function (e){
console.log("ee",e.target);
console.log(this);
// console.log("nodeName",e.target.nodeName);
// console.log("tagName",e.target.tagName);
if(e.target.tagName =="BUTTON"){
this.removeChild(e.target.parentNode);
//e.target.parentNode.remove();
}else if(e.target.tagName == "SPAN"){
//第一步判断是span标签,第二步根据target点谁选择谁来改变点击对象的颜色样式
e.target.style.color ="#0099ff";
}
}
</script>
</body>