【JS基础】e.stopPropagation() 阻止事件冒泡

tech2025-09-22  8

e.stopPropagation()阻止事件冒泡

初始例子

<table border="1"> <tr> <td><span>冒泡事件测试</span></td> <td><span>冒泡事件测试2</span></td> </tr> </table> $('table').on('click', function(e) { alert('table alert!') }) $('tr').on('click', function() { alert('tr alert') }) $('span').on('click', function() { alert('span alert!') })

初始效果

我们会看到这样的情况:span alert -> td alert -> table alert。这就叫事件冒泡。就是从下到上,从里到外,事件依次触发。

有的时候我们不希望事件冒泡咋办?

$(function() { $('table').on('click','span',function(e) { alert('span alert!') e.stopPropagation(); }) $('table').on('click', function() { alert('table alert!') }) })

这样,点击span时,弹出"span alert!"对话框即结束,然后禁止事件冒泡,“table alert!”对话框即不会触发

如果想获得事件相关信息,就要给匿名方法加一个e对象,e就是事件对象

最新回复(0)