您好,欢迎来到冠东财富。
搜索
您的当前位置:首页jquery阻止事件冒泡及其解决方法

jquery阻止事件冒泡及其解决方法

来源:冠东财富


html
<p id="box"> 
 <a href="javascript:;" class="delete">init html</a>
</p> 
<button id="add">add html</button>
jq
 $(function() {

 // 用click事件
 $(document).click( function(event) {
 console.log('click');
 event.stopPropagation();
 });

 // 用delegate事件
 $(document).delegate('.delete','click', function(event) {
 console.log('delegate');
 event.stopPropagation();
 });

 // 用live事件
 $('.delete').live('click', function(event) {
 console.log('live');
 event.stopPropagation();
 //return false;
 });

 // 新添加的a标签
 $('#add').click(function() {
 var html = '<a href="javascript:;" class="delete">new html 1</a>';
 $('#box').append(html);
 });

 $('#box').click(function() {
 console.log('box emit');
 });

});

解决办法:
我们知道event.stopPropagation()对click阻止冒泡有效,那就可以在新动态添加的标签上绑定click事件。

Copyright © 2019- guangdonghui.cc 版权所有

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务