我的网站上有一个过滤器侧边栏,其中包含最初全部隐藏的不同类别。当您单击某个类别时,会显示选项,并且类别旁边的箭头会从下变为上。这有效
当您单击下一个类别时,其他类别应该关闭。这也有效。
不起作用的是正在关闭的类别的箭头变回向下(它们保持向上)。
除此之外,我认为我的代码太大了,应该有一种更简单的方法来使用 $this 但我找不到正确的解决方案。希望有人能帮助我!
https://jsfiddle.net/mxqp4c4h/14/
$(document).ready(function() {
$("div.filterdropdown").each(function() {
var a = $(this);
$(".dropdowntitle", a).click(function(i) {
return i.preventDefault(), $div = $(".dropdowncontent", a), $div.toggle(), $("div.dropdowncontent").not($div).hide(), !1
})
})
});
$(document).ready(function() {
$("div.filterdropdown").each(function() {
var a = $(this);
$(".dropdowntitle", a).click(function(i) {
return i.preventDefault(), $div = $(".fa-chevron-down", a), $div.toggle(), $("div.fa-chevron-down").not($div).hide(), !1
})
})
});
$(document).ready(function() {
$("div.filterdropdown").each(function() {
var a = $(this);
$(".dropdowntitle", a).click(function(i) {
return i.preventDefault(), $div = $(".fa-chevron-up", a), $div.toggle(), $("div.fa-chevron-up").not($div).hide(), !1
})
})
});
最佳答案
只需使用 JS 即可简化。
$(document).ready(function() {
$(".dropdowntitle").click(function(i) {
var thisEle = $(this).parent().find(".dropdowncontent");
var oriVisible = false;
if (thisEle.is(":visible")) {
oriVisible = true;
}
// Reset
$(".dropdowncontent").hide();
$(".fa-chevron-down").show();
$(".fa-chevron-up").hide();
if (oriVisible) {
// do nothing
} else {
thisEle.show();
$(this).find(".fa-chevron-down").hide();
$(this).find(".fa-chevron-up").show();
}
});
});
.clear { display:block; }
.filter { position:relative; width:100%; display:inline-block; clear:both; }
.dropdowntitle { position:relative; width:100%; display:inline-block; clear:both; }
h1 { padding:0; margin:0; float:left; }
i.fa {float:left;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet"/>
<div class="filter filterdropdown">
<div class="dropdowntitle">
<h1>Style</h1>
<i class="fa fa-chevron-down"></i>
<i class="fa fa-chevron-up" style="display:none;"></i>
</div>
<div class="dropdowncontent" style="display:none;">
A
</div>
</div>
<div class="clear"></div>
<div class="filter filterdropdown">
<div class="dropdowntitle">
<h1>Accomodation type</h1>
<i class="fa fa-chevron-down"></i>
<i class="fa fa-chevron-up" style="display:none;"></i>
</div>
<div class="dropdowncontent" style="display:none;">
B
</div>
</div>
关于javascript - 打开 div 并关闭所有其他 div 并更改 onclick 箭头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48858945/