[英]Jquery click outside multiple div/elements
There are two sections targetDiv1
and targetDiv2
(not nested). 有两个部分
targetDiv1
和targetDiv2
(未嵌套)。 And another section collapsibleDiv
. 和另一部分
collapsibleDiv
。 I need to run a function(be it collapsing the div) on clicking outside the element targetDiv2
; 我需要在元素
targetDiv2
外部单击时运行一个函数(折叠div); but the function should not be triggerred when clicking targetDiv1
. 但是单击
targetDiv1
时不应触发该功能。 With the below code I'm unable to achieve this.. Any help would be great... 使用下面的代码,我将无法实现此目标。任何帮助都将非常棒...
$(document).click(function(e) {
if(!$(e.target).closest('.targetDiv1').length && !$(e.target).is('.targetDiv1')) {
$('.collapsibleDiv').slideDown();
}
});
JSFiddle as per the answer from @Kweiss https://jsfiddle.net/vn8gmu8g/ JSFiddle根据@Kweiss https://jsfiddle.net/vn8gmu8g/的答案
You want the function to execute on a click outside Div1 or Div2, but your code only excludes Div1. 您希望函数在Div1或Div2之外的单击上执行,但是您的代码仅排除Div1。 Just add Div2 as well.
只需添加Div2。
$(document).click(function(e) {
var $target = $(e.target);
if(!$target.closest('.targetDiv1').length && !$target.hasClass('targetDiv1') &&
!$target.closest('.targetDiv2').length && !$target.hasClass('targetDiv2')) {
$('.collapsibleDiv').slideDown();
}
});
Saving e.target
in a variable and using hasClass()
will make your code faster. 将
e.target
保存在变量中并使用hasClass()
将使您的代码更快。
$(".targetDiv2").click(function(){
$('.collapsibleDiv').slideDown();
})
It does what you want. 它可以满足您的需求。 It will collapse when you click
div2
. 单击
div2
它将折叠。
Try this : you have to add same if conditions for div2 试试这个:如果div2的条件必须添加相同
$(document).click(function(e) {
var $clickedElement = $(e.target);
if(!$clickedElement.closest('.targetDiv1').length && !$clickedElement.is('.targetDiv1') && !$clickedElement.closest('.targetDiv2').length && !$clickedElement.is('.targetDiv2')) {
$('.collapsibleDiv').slideDown();
}
});
I created a demo , and I would say, it is working... 我创建了一个演示 ,我会说它正在工作...
$(document).click(function(e) {
if(!$(e.target).closest('.targetDiv1').length && !$(e.target).is('.targetDiv1')) {
$('.collapsibleDiv').slideDown();
alert("OK");
}
});
If you click on targetDiv1 -> nothing happens
如果单击targetDiv1->没有任何反应
If you click on targetDiv2 -> alert
如果您单击targetDiv2->警报
If you click anywhere else -> alert
如果您单击其他任何位置->警报
I would say, this is what you described. 我会说,这就是你所描述的。
下面应该工作
$(document).click(function(e) { var target = $(e.target); if(!target.hasClass('.targetDiv1') && !target.hasClass('.targetDiv2')) { // perform you operation } });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.