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

黄舟
黄舟Original
2017-06-26 10:16:392623browse

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>

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");  } );

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");
});

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");
});
$(&#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");
});

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!

Statement:
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