子元素会继承父元素的事件,也就是说处单击了子元素,会执行父元素的事件相应程序
这种设计的优点在于,如果一个元素中的子元素过多,直接给父元素绑定事件即可,而不用为每一个子元素都绑定相同的事件处理程序
如果不希望子元素继承父元素的事件处理程序,则为子元素也注册单击事件,然后在此事件中,阻止冒泡
<!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>
<style>
div{
width: 200px;
background-color: gray;
}
label{
position: absolute;
top: 50px;
}
</style>
</head>
<body>
<div class="box">
<input type="radio" name="" id="man">
<label for="">男</label>
</div>
</body>
</html>
<script>
document.querySelector('.box').onclick=function(){
console.log(1)
}
document.querySelector('.box label').onclick=function(e){
e.stopPropagation()
}
</script>
此时,单击文字男,就不会触发父元素的处理程序了,注意,此时我将 label 的 for 属性的值设置为空
for 属性的意义在于,出发目标元素的获取焦点事件,其实就是触发的目标元素的单击事件
波比如,我们修改 label 元素
<label for="man">男</label>
然后再给 单选按钮绑定单击事件
document.querySelector('#man').onclick=function(){
console.log('checked')
}
然后单击文字男
可以看到确实触发了 单选按钮的单击事件,当然后面输出的1 是因为事件冒泡,导致又间接的触发了 div 的单击事件
完整代码
<!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>
<style>
div{
width: 200px;
background-color: gray;
}
label{
position: absolute;
top: 50px;
}
</style>
</head>
<body>
<div class="box">
<input type="radio" name="" id="man">
<label for="man">男</label>
</div>
</body>
</html>
<script>
document.querySelector('.box').onclick=function(){
console.log(1)
}
document.querySelector('.box label').onclick=function(e){
e.stopPropagation()
}
document.querySelector('#man').onclick=function(e){
e.stopPropagation()
console.log('checked')
}
</script>