Home  >  Article  >  Web Front-end  >  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
WBOYOriginal
2016-05-16 16:38:031427browse

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>

js:

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

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

Just add a sentence to stop bubbling.

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