jquery: delegate repeatedly triggers event Solution to the problem
<html> <head> <script type="text/javascript" src="http://www.w3school.com.cn/jquery/jquery.js"></script> <style> div{border:1px solid balck;padding:5px;margin:2px;} </style> </HEAD> <body> <div id="div1" >div1 <div id="div1_1" >div1_1 <div id="div1_1_1" >div1_1_1 <span style="background:red; display:block; width:25px; height:25px;">span</span> </div> </div> <div id="div1_2" >div1_2 </div> </div> </body> <script type="text/javascript"> $('body').delegate('body>div','click',function(){alert("div");}); $('body').delegate('div>span','click',function(){alert("span");}); </script> </HTML>
How to avoid triggering the div click event when clicking the span area? ? ?
$('body').delegate('div>span','click',function(evt){ evt.stopPropagation(); alert("span"); } );
Cancel the bubbling of span's click event. The answer has been given on the first floor: e.stopPropagation()~
Method 1. Prevent event bubbling
Method 2. Determine the event trigger,
$('body').delegate('body>div','click',function(){ if(e.target!=$('#div1_1_1').find('span')[0]) alert("div"); });
Method 1. Prevent the event from bubbling
Method 2. Determine the event trigger,
$('body').delegate('body>div','click',function(){ if(e.target!=$('#div1_1_1').find('span')[0]) alert("div"); });
$('body').delegate('body>div','click',function(e){ if(e.target!=$('#div1_1_1').find('span')[0]) alert("div"); });
I tried it
The above is the detailed content of jquery: Solution to the problem of delegate repeatedly triggering events. For more information, please follow other related articles on the PHP Chinese website!