2012-02-07 50 views

Respuesta

315

Si el e.target es el mismo elemento que this, no ha hecho clic en un descendiente.

$('.foobar').on('click', function(e) { 
 
    if (e.target !== this) 
 
    return; 
 
    
 
    alert('clicked the foobar'); 
 
});
.foobar { 
 
    padding: 20px; background: yellow; 
 
} 
 
span { 
 
    background: blue; color: white; padding: 8px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class='foobar'> .foobar (alert) 
 
    <span>child (no alert)</span> 
 
</div>

+0

Esa respuesta explica [esto] (http://stackoverflow.com/questions/9146163/jquery-closest-with-attribute-filter#comment11499568_9146163) comment – gdoron

+0

@gdoron: Adam está siendo muy amable. :) –

+0

puede por favor responder a mi [pregunta] (http://stackoverflow.com/q/9193293/601179) ... =) – gdoron

17
//bind `click` event handler to the `.foobar` element(s) to do work, 
//then find the children of all the `.foobar` element(s) 
//and bind a `click` event handler to them that stops the propagation of the event 
$('.foobar').on('click', function() { ... }).children().on('click', function (event) { 
    event.stopPropagation(); 
    //you can also use `return false;` which is the same as `event.preventDefault()` and `event.stopPropagation()` all in one (in a jQuery event handler) 
}); 

Esto evitará la propagación (burbujeo) del evento click en cualquiera de los niños el elemento (s) del elemento (s) .foobar por lo que el caso no lo hará llegue al elemento .foobar para activar su controlador de eventos.

Aquí es una demostración: http://jsfiddle.net/bQQJP/

19

Puede utilizar burbujeo a su favor:

$('.foobar').on('click', function(e) { 
    // do your thing. 
}).on('click', 'div', function(e) { 
    // clicked on descendant div 
    e.stopPropagation(); 
}); 
2
$(".advanced ul li").live('click',function(e){ 
    if(e.target != this) return; 
    //code 
    // this code will execute only when you click to li and not to a child 
}) 
22

Hay otra forma en que funciona si no le importa solamente dirigidas a nuevos navegadores. Solo agregue el CSS

pointer-events: none; 

para cualquier niño del div que desee capturar el clic. He aquí las mesas de apoyo

http://caniuse.com/#feat=pointer-events

+2

este es el mejor truco, gracias – Rickie

+0

Buena solución, gracias. – tulsluper

+1

Sepa que debería evitar escribir comentarios de agradecimiento, pero puedo besarlo para esto :-) –

0

que tenía el mismo problema y se acercó con esta solución (basados ​​en las otras respuestas)

$(".newsletter_background").click(function(e) { 
    if (e.target == this) { 
     $(".newsletter_background").hide(); 
    } 
}); 

Básicamente se dice si el objetivo es el div continuación, ejecute el código de lo contrario no hacer nada (no ocultarlo)

Cuestiones relacionadas