js阻止事件冒泡
直接上代码
<!DOCTYPE html> <html> <head> <title>js事件委托测试</title> </head> <body> <div id='box'></div> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <style type="text/css"> .item{ background-color: yellow; margin: 10px; padding: 10px; color: black; } </style> <script type="text/javascript"> $(document).ready(function(){ var addItem = function(){ htmlStr = '' for(var i=0; i<10; i++){ htmlStr += (`<div class="item">${i}</div>`) } $('#box').html(htmlStr) } addItem() $('.item').bind('click', function(event){ alert('item') event.stopPropagation()// 阻止冒泡 }) $('#box').bind('click', function(event){ alert('box') }) }) </script> </body> </html>
jquery.bind()
查询官方api可看见回调方法传入值为event, 通过event就能阻止事件后续传播
js事件模型
参考
Become a Linux Programmer