Fire ul tag click event not li with jquery

匿名 (未验证) 提交于 2019-12-03 00:56:02

问题:

How can affect click event only ul tag not all li with jQuery?

<!-- HTML --> <ul class="wrap">     <li>test1</li>     <li>test2</li>     <li>test3</li> </ul> 

I tried jquery like this.But it doesnt work.

//Javascript jQuery("ul.wrap").not(jQuery("ul > li")).click(function(){       //fire only ul }); 

How can we do this?

回答1:

Events 'bubble' up the DOM to their parent elements. What you need to do is attach the event to the ul, and another event on the child li elements which uses stopPropagation():

jQuery("ul.wrap")     .on('click', function(){         // do something...     })     .on('click', 'li', function(e) {         e.stopPropagation();     }); 


回答2:

You can simply do it with this code:

jQuery('.wrap').click(function (event) {         if ( !$(event.target).is( "li" ) ) {         console.log('ul clicked!');     }  }); 

You can see an example with background colors that shows the ul and the li here: http://jsfiddle.net/S67Uu/2/



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!