最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Fire ul tag click event not li with jquery - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Jun 21, 2014 at 15:02 mikelamar 1881 silver badge6 bronze badges asked Jun 21, 2014 at 14:30 user3763026user3763026 833 silver badges11 bronze badges 3
  • But ul will have li after all.What do u mean by Click on ul – Pratik Joshi Commented Jun 21, 2014 at 14:32
  • jsfiddle/v5eh8/1 Check this fiddle.UL has LI so thought you click on li , it will be as if UL is clicked – Pratik Joshi Commented Jun 21, 2014 at 14:34
  • I mean jquery click event will affect except all li. – user3763026 Commented Jun 21, 2014 at 14:35
Add a ment  | 

2 Answers 2

Reset to default 4

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/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();
    });
发布评论

评论列表(0)

  1. 暂无评论