简单说下事件委托与阻止冒泡
html:
1
2
3
4
5
6
7
8
9
10
|
< 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:
1
2
3
4
5
6
|
$( "ul[data-type='cityPick']" ).on( 'click' , function (){ alert( "父元素ul被点击" ); }); $( "ul[data-type='cityPick']" ).on( 'click' , 'li' , function (){ alert( "子元素li被点击" ); }); |
当点击具体的li元素时,发现ul的事件也被触发了,这是我们不想看到的。
解决:
1
2
3
4
5
6
7
|
$( "ul[data-type='cityPick']" ).on( 'click' , function (){ alert( "父元素ul被点击" ); }); $( "ul[data-type='cityPick']" ).on( 'click' , 'li' , function (e){ e.stopPropagation(); //阻止冒泡 alert( "子元素li被点击" ); }); |
加一句阻止冒泡即可。