简体   繁体   中英

prevent click event from element but not from <a> children

my code looks like this:

<div class="disabledClickevent">
  <ul>
    <li><a>link1</a></li>
    <li><a>link2</a></li>
  </ul>
</div>

the div has a click event that gets disabled with return false; my problem is that this also disables the <a> links

 $(document).on('click','.disabledClickevent' function(e) {
   if( e.target !== this ) 
   //clicked out side
 return;    
    //clicked inside
});

I would do this:

$(".disabledClickevent").on("click", ":not(a)", function(e) {
    //do stuff with your div
});

This excludes a from the click event.

Could be a solution:

$('.disabledClickevent').on('click',function(e){
     if($(e.target).is(':not(a)'))
        return false;
});

Or set click handler to links:

$('.disabledClickevent a').click(function(e){
    e.stopPropagation();
});

you can use the :not() selector in jQuery

check this link out http://api.jquery.com/not-selector/

hope this helps.

If you don't plan to add new "disabledClickevent" divs to the page via Javascript, you could just do this:

$('.disabledClickevent').click(function() {...});

or

$('.disabledClickevent').bind('click', function() {...});

That attaches the event only to the already-existing div, without doing any sort of delegation, so the links will just work normally as you want them to.

To be clear, this is only a viable solution if all of the "disabledClickevent" divs that you plan to have already exist on the page at the time that you bind the event.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM