可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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/