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?
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/
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();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.