Home > Web Front-end > JS Tutorial > jquery: Solution to the problem of delegate repeatedly triggering events

jquery: Solution to the problem of delegate repeatedly triggering events

黄舟
Release: 2017-06-26 10:16:39
Original
2607 people have browsed it

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">
$(&#39;body&#39;).delegate(&#39;body>div&#39;,&#39;click&#39;,function(){alert("div");});
$(&#39;body&#39;).delegate(&#39;div>span&#39;,&#39;click&#39;,function(){alert("span");});
</script>
</HTML>
Copy after login

How to avoid triggering the div click event when clicking the span area? ? ?

$(&#39;body&#39;).delegate(&#39;div>span&#39;,&#39;click&#39;,function(evt){ evt.stopPropagation(); alert("span");  } );
Copy after login

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,

$(&#39;body&#39;).delegate(&#39;body>div&#39;,&#39;click&#39;,function(){
if(e.target!=$(&#39;#div1_1_1&#39;).find(&#39;span&#39;)[0]) alert("div");
});
Copy after login
Copy after login

Method 1. Prevent the event from bubbling
Method 2. Determine the event trigger,

$(&#39;body&#39;).delegate(&#39;body>div&#39;,&#39;click&#39;,function(){
if(e.target!=$(&#39;#div1_1_1&#39;).find(&#39;span&#39;)[0]) alert("div");
});
Copy after login
Copy after login
$(&#39;body&#39;).delegate(&#39;body>div&#39;,&#39;click&#39;,function(e){
if(e.target!=$(&#39;#div1_1_1&#39;).find(&#39;span&#39;)[0]) alert("div");
});
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template