Home > Web Front-end > JS Tutorial > Event delegation and preventing bubbling prevent its parent element event from triggering_jquery

Event delegation and preventing bubbling prevent its parent element event from triggering_jquery

WBOY
Release: 2016-05-16 16:38:03
Original
1453 people have browsed it

Briefly talk about event delegation and preventing bubbling

html:

<ul class="clearfix" data-type="cityPick"> 
<li class="active_sort_opts" data-id="0">全部</li> 
<li data-id="88">纽约</li> 
<li data-id="119">洛杉矶</li> 
<li data-id="138">拉斯维加斯</li> 
<li data-id="84">夏威夷</li> 
<li data-id="120">旧金山</li> 
<li data-id="105">奥兰多</li> 
<li data-id="118">西雅图</li> 
</ul>
Copy after login

js:

$("ul[data-type='cityPick']").on('click',function(){ 
alert("父元素ul被点击"); 
}); 
$("ul[data-type='cityPick']").on('click','li',function(){ 
alert("子元素li被点击"); 
});
Copy after login

When clicking on a specific li element, it is found that the ul event is also triggered, which is what we don't want to see.

Solution:

$("ul[data-type='cityPick']").on('click',function(){ 
alert("父元素ul被点击"); 
}); 
$("ul[data-type='cityPick']").on('click','li',function(e){ 
e.stopPropagation();//阻止冒泡 
alert("子元素li被点击"); 
});
Copy after login

Just add a sentence to stop bubbling.

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