简体   繁体   English

如何将click事件绑定到文档,以便仅在未单击任何对象时才触发

[英]How to bind a click event to the document so that it fires only when no object is clicked

I would like an event to fire whenever something other than a DOM element is clicked, and a separate event when an image is clicked. 我希望每当单击DOM元素以外的内容时触发一个事件,而当单击图像时触发一个单独的事件。

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. 如果用户单击img元素,则会提示“ img”,否则将停止单击事件。

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/ ? http://www.jsfiddle.net/U2Szn/

This should work, but just img isn't enough. 这应该可以,但是仅img是不够的。 It could be triggering from the img container. 它可能是从img容器触发的。 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. 我认为您需要一个选择器,例如$('p,div,img,a,input,textarea,span,ul,ol,dl,li,dd,dt,table,tr,td')和任何其他标签可以想到将其完成。 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 如果您希望在单击html和/或body或单击img时触发事件,则应执行以下操作: 实时示例

$(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')
});​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM