Perform function when clicking except on specific item with jQuery

1

I have the following code:

$(".teste").click(function() {
    return false;
});

In this div .teste I have links with class .link and I want the return false to occur when I click on the div, but that return false does not occur if I click on the links ( .link ) which are within the div. Already tried:

$(".teste").not("a.link").click(function() {
    return false;
});

I also tried:

$(".teste:not(a)").click(function() {
    return false;
});

But both did not work.

HTML (example):

<div class="teste">
    <div class="outradiv"></div>

    <div class="maisumadiv">
        <a href="/teste" class="link">Link...</a>
    </div>
</div>
    
asked by anonymous 10.07.2015 / 21:52

4 answers

2

You can capture the target of the event, if it is a link you return true ;

$('.teste').on('click', function(e) {
  if($(e.target).is('a')) return true;
  alert('Click');
  return false;
});
.teste {
  height: 200px;
  background-color: gray;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='teste'>
  <div><a href='http://www.google.com.br'>Link 1</a></div>
  <div><a href='http://pt.stackoverflow.com/'>Link 2</a></div>
</div>
    
10.07.2015 / 22:14
3

Well, you already have several answers, but I'll propose another method:

$('.teste').click(function(e) {
   return !(e.target == this);
});
.teste {
    background: yellow;
    padding: 20px;
}
<div class="teste">
    <a href="http://jsfiddle.net">teste</a>
</div>

This works because the link click handling is delegated to a higher level in the hierarchy, the div. The target of the event is the clicked element, but the this is always the element where you "tied" the event (in this case, the div). So if you click something other than the div itself, that is, anything inside the div, the event is not canceled ( return true ), otherwise it is canceled ( return false ).

    
10.07.2015 / 22:27
0

Maybe this is what you want:

$(".teste, .link").on('click', function() {
     if ($(this).attr('class')=='link') {
        return true;
     } 
  return false;
});
    
10.07.2015 / 22:10
0
$(".teste").find(".link").click(function() {
    return true;
});
    
10.07.2015 / 22:20