Home > Article > Web Front-end > Event delegation and preventing bubbling prevent its parent element event from triggering_jquery
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.