Domanda

I want to alert something when user clicked anywhere in the document except the div that has class = 'reset_btn'. I have tried both not() and :not(selector) but they are not working.

This is my code.

$('document').not('.reset_btn').click(function(){
   alert('Something');
});

I have created a demo in JSFiddle. In demo they aren't alert anything. It should alert when I clicked any area outside the div and should not alert when I clicked in div area.

Any suggestion? Thank you very much.

È stato utile?

Soluzione

$('document') is not a valid selector, since there's no document tag name. You could instead use $(document), which'll use the document element, but that's not needed here. Just use :not() directly:

$(':not(.reset_btn)').click(function(){
   alert('Something');
});

To optimize this further, you should use event delegation:

$(document).on('click', ':not(.reset_btn)', function(){
   alert('Something');
});

Altri suggerimenti

You can use on to delegate event to document.

$(document).on("click", ':not(.reset_btn)').click(function(){
   alert('Something');
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top