单击时显示同级<i>

时间:2019-04-03 08:27:52

标签: jquery html

当我单击第一个时,我试图显示隐藏的<i>。我尝试阅读有关此内容的内容,并尝试了siblings()等的不同变体,但我无法使其正常工作。有人可以解释我该怎么做吗?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="locationactions">
  <i class="fas fa-trash-alt"></i>
  <i class="fas fa-check" style="display: none;"></i>
</div>
$('.adminapp .locationactions i').click(function() {
  if (currentApp != "adminapp") 
    return;

  $(this).closest('i').show(150);
});

1 个答案:

答案 0 :(得分:2)

问题是因为closest()寻找最近的 parent 元素,而您要定位的i是同级的。因此,请使用siblings('i')next('i')

var currentApp = 'adminapp';

$('.adminapp .locationactions i').click(function() {
  if (currentApp != "adminapp")
    return;

  $(this).next('i').show(150); // looks at the following sibling element ONLY
  // Alternative:
  // $(this).siblings('i').show(150); // looks at ALL siblings
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="adminapp">
  <div class="locationactions">
    <i class="fas fa-trash-alt">fa-trash-alt</i>
    <i class="fas fa-check" style="display: none;">fa-check</i>
  </div>
</div>