在单击时最接近 class 淡入并与淡出同级

Getting closest class to fadeIn on click and sibling to fadeOut

我正在尝试制作一个类似切换菜单的菜单来显示不同的信息,但是我的尝试没有奏效。

我正在寻找的是,如果用户单击任何标题(A、B 或 C),描述将 fadeIn。这就是为什么我尝试使用 closest() 方法来获取与标题相关联的描述。然后当用户点击不同的标题时,关闭当前标题,打开另一个标题。

有没有人看出我做错了什么?

$(".service-list-title").on("click", function(event) {
  $(this).closest('.service-list-description').fadeIn(300).siblings().closest('.service-list-description').fadeOut(300);
});
.service-list-title {
  display: block;
  color: #333333;
  font-size: 1.1rem;
  letter-spacing: .1rem;
  margin: 20px 0px;
  padding: 0 10px 0 25px;
  cursor: pointer;
  transition: all .35s ease;
  -webkit-transition: all .35s ease;
}

.service-list-description {
  display: none;
  color: #333333;
  font-size: .9rem;
  margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="service-list">
  <li class="service-list-title">A</li>
  <p class="service-list-description">This is the content for A</p>
</div>
<div class="service-list">
  <li class="service-list-title">B</li>
  <p class="service-list-description">This is the content for B</p>
</div>
<div class="service-list">
  <li class="service-list-title">C</li>
  <p class="service-list-description">This is the content for C</p>
</div>

下面的函数应该可以满足您的要求:

$(".service-list-title").on("click", function(event) {
  $('.service-list-description').fadeOut(300); // Close any that's open
  $(this).siblings('.service-list-description').fadeIn(300); // Open new
});

Fiddle: https://jsfiddle.net/beekvang/oro9ue3k/

您的代码存在问题,您使用的是 closest(),它会查找父元素,而不是 next()siblings(),它会在同一级别搜索元素。

但是,您可以通过将事件处理程序附加到 .service-list 元素并使用 find() 将所需元素获取到 fadeToggle() 来简化逻辑。然后,您可以 select 所有其他 .service-list-description 元素并调用 fadeOut() 来隐藏它们。试试这个:

$(".service-list").on("click", function(event) {
  var $target = $(this).find('.service-list-description').fadeToggle(300);
  $('.service-list-description').not($target).fadeOut(300);
});
.service-list-title {
  display: block;
  color: #333333;
  font-size: 1.1rem;
  letter-spacing: .1rem;
  margin: 20px 0px;
  padding: 0 10px 0 25px;
  cursor: pointer;
  transition: all .35s ease;
  -webkit-transition: all .35s ease;
}

.service-list-description {
  display: none;
  color: #333333;
  font-size: .9rem;
  margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="service-list">
  <li class="service-list-title">A</li>
  <p class="service-list-description">This is the content for A</p>
</div>
<div class="service-list">
  <li class="service-list-title">B</li>
  <p class="service-list-description">This is the content for B</p>
</div>
<div class="service-list">
  <li class="service-list-title">C</li>
  <p class="service-list-description">This is the content for C</p>
</div>