问题
Javascript code:
$(".div1").click(function(event){
event.stopPropagation();
$(".div1 div").slideToggle();
});
$(".div2").click(function(event){
event.stopPropagation ();
$(".div2 div").slideToggle();
});
$(document).click(function(event){
$(".div1 div,.div2 div").slideUp();
});
Suppose I click .div1
& .div1 div
slides down. Then i click .div2
But as event.stopPropagation
is executed, .div1 div
doesnot slide up. So what should i do? I dont want to put this code $(".div1 div").slideUp();
as it makes no sense when there'll be too many divs like this
回答1:
Never use Event.stopPropagation()
. All the layers of any application should always, at any point, be able to register an event happened.
Instead use the event.target
and traverse with .closest()
to achieve the same.
The following will handle infinite numbers of DIVs, so you don't need to rewrite your code. (PS: just add a .box
to your parent elements to make all simpler)
$(".box").on("click", function(event){
const $div = $(this).find('div');
$('.box > div').not($div).slideUp();
$div.slideToggle();
});
$(document).on("click", function(event){
if (!$(event.target).closest(".box").length) {
$(".box > div:visible").slideUp();
}
});
/*QuickReset*/ * {margin:0; box-sizing:border-box;}
.box{
background:#eee;
width:160px;
padding:10px 0;
margin:10px;
}
.box h2{
cursor:pointer;
}
.box div{
display:none;
background:#aaa;
color:#cf5;
}
Click on 'body' to close opened DIVs
<div class="div1 box">
<h2>DIV 1</h2>
<div>Lorem <br>Ipsum<br>....</div>
</div>
<div class="div2 box">
<h2>DIV 2</h2>
<div>Lorem <br>Ipsum<br>....</div>
</div>
<div class="div3 box">
<h2>DIV 3</h2>
<div>Lorem <br>Ipsum<br>....</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
来源:https://stackoverflow.com/questions/11569082/selective-stoppropagation-jquery