Fire ul tag click event not li with jquery

How to affect the click only event, only the ul tag is 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 does not work.

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

How can we do this?

+4
source share
2 answers

The bubble event up the DOM to their parent elements. What you need to do is attach the event to ulanother event of the child elements li, which uses stopPropagation():

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

You can simply do this with this code:

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

You can see an example of a floral background, which shows the ul and li here: http://jsfiddle.net/S67Uu/2/

+4

Source: https://habr.com/ru/post/1545486/


All Articles