单击元素外部时的jQuery触发事件

tpa*_*pae 31 javascript jquery

$(document).click(function(evt) {
    var target = evt.currentTarget;
    var inside = $(".menuWraper");
    if (target != inside) {
        alert("bleep");
    }

});
Run Code Online (Sandbox Code Playgroud)

我试图找出如何制作它,以便如果用户点击某个div(menuWraper)之外,它会触发一个事件..我意识到我可以让每次点击触发一个事件,然后检查点击的currentTarget是否是与从$(".menuWraper")中选择的对象相同.但是,这不起作用,currentTarget是HTML对象(?)而$(".menuWraper")是Object对象?我很迷茫.

use*_*716 68

只需menuWraper调用元素event.stopPropagation(),使其click事件不会冒泡到document.

试一试: http ://jsfiddle.net/Py7Mu/

$(document).click(function() {
    alert('clicked outside');
});

$(".menuWraper").click(function(event) {
    alert('clicked inside');
    event.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)

或者,你可以return false;代替使用event.stopPropagation();


小智 18

如果您有下拉菜单等子元素

$('html').click(function(e) {
  //if clicked element is not your element and parents aren't your div
  if (e.target.id != 'your-div-id' && $(e.target).parents('#your-div-id').length == 0) {
    //do stuff
  }
});
Run Code Online (Sandbox Code Playgroud)


Nic*_*ver 12

这里最常见的应用是关闭单击文档,但不是当它来自该元素时,为此你要停止冒泡,如下所示:

$(".menuWrapper").click(function(e) {
  e.stopPropagation(); //stops click event from reaching document
});
$(document).click(function() {
  $(".menuWrapper").hide(); //click came from somewhere else
});
Run Code Online (Sandbox Code Playgroud)

所有的都在这里做是防止点击来自冒泡(通过event.stopPrpagation()),当它从内传来.menuWrapper元素.如果没有发生这种情况,那么点击来自其他地方,并且默认情况下会让它达到目标document,如果它到达那里,我们会隐藏这些.menuWrapper元素.