У меня есть окно уведомлений (абсолютно позиционированное div), и я хочу, чтобы оно закрывалось при нажатии всего, что находится за пределами этого окна.
Я старался:
<div id="#notifWindow">
<div id="notifs">Notifications...</div>
<a class="ajax" data-bla="blabla">Click for ajax</a>
</div>
$(document).on(function(event){
// If clicking over child elements stopPropagation() else window is closed.
if ($(this).closest('#notifWindow').length) event.stopPropagation();
else $('#notifWindow').hide();
})
// Just for your information
$(document).on('click', 'a.ajax', function(event){
// If I use onclick=event.stopPropagation() in #notifWindow this ajax fails
})
Здесь $(this) — это не элемент, вызывающий событие, а документ.
Спасибо за уделенное время.
РЕШЕНИЕ
// Every .ajax inside #notifWindow (dinamically ajax generated) is executed.
$('#notifWindow').on('click', '.ajax', function(event) {
alert('This ajax is executed!');
});
// If clicking everywhere inside #notifWindow the propagation of 'click' is stopped
$('#notifWindow').on('click', function(event) {
event.stopPropagation();
$(document).on('click', '#open', function(event){
$('#notifWindow').slideDown();
event.stopInmediatePropagation(); // It avoid other click events for (document).
});
// Hides the window clicking everywhere
$(document).on('click', function(event) {
$('#notifWindow').hide();
});
Спасибо вам всем :-)
stopPropagation
, когда он достигdocument
, слишком поздно. - person pimvdb   schedule 11.07.2012