冒泡事件即:触发子节点中的方法,父节点也注册了相同的方法,会导致父节点也响应该方法。
例如以下:店家button按钮,触发bubbling事件。
<html>
<body>
<div onclick="one()">
<div onclick="two()">
<div onclick="three()">
<button onclick="bubbling()">按钮</button>
</div>
</div>
</div>
</body>
<script>
function one() {
console.log("one")
}
function two() {
console.log("two")
}
function three() {
console.log("three")
}
function bubbling() {
console.log("bubbling")
}
</script>
依次打印出: bubbling,three,two,one,一级一级往上一层触发。

解决方法:事件结束后添加event.stopPropagation().注:ie8以下不支持
<html>
<body>
<div onclick="one()">
<div onclick="two()">
<div onclick="three()">
<button onclick="bubbling()">按钮</button>
</div>
</div>
</div>
</body>
<script>
function one(e) {
console.log("one")
}
function two() {
console.log("two")
}
function three(e) {
console.log("three")
}
function bubbling() {
console.log("bubbling")
event.stopPropagation();
}
</script>
</html>

952

被折叠的 条评论
为什么被折叠?



