冠东财富
您的当前位置:首页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事件。

显示全文