I would like an event to fire whenever something other than a DOM elemen开发者_如何转开发t is clicked, and a separate event when an image is clicked.
Right now I have:
$( document ).click( function() { /*do whatev*/ } );
and in another place:
$( "img" ).click( function( e ) {
e.stopPropagation();
/*do whatev*/
} );
it does not work. both events are fired. any other ideas?
Simple and concise:
jQuery(document).click(function(event) {
if (jQuery(event.target).is('img'))
{
alert('img');
}
else
{
// Reject event
return false;
}
});
If the user clicks on an img element 'img' is alerted, otherwise the click event is stopped.
something like this:
$('*').click(function(ev) {
ev.stopPropagation();
if ($(this).is('img')) alert('img');
else if($(this).is('div')) alert('div');
else alert('something else');
});
http://www.jsfiddle.net/U2Szn/ ?
This should work, but just img
isn't enough. It could be triggering from the img container. I think you'd need a selector like $('p,div,img,a,input,textarea,span,ul,ol,dl,li,dd,dt,table,tr,td')
and any other tag you can think of to pull it off. This might have performance issues.
If you want an event to fire when the html
and/or body
is clicked or an img
is clicked something like this should work: Live Example
$(document).click(function(e) {
if($(e.target).is('html')){
alert('this is the html element');
}else if($(e.target).is('body')){
alert('this is the body element');
}
});
$("img").click(function(e) {
e.stopPropagation();
alert('img')
});
精彩评论