首页 > 解决方案 > 使用 jQuery 和 JavaScript 隐藏特定元素

问题描述

我们的代码有问题:

function remove_single_entry_if_empty() {
  $(".single-entry").each(function() {
  var ids = $(this).attr('id');
      let a = (ids);
        for ( let i = 0; i < a.length; a++ ) {
          let x = document.getElementById(a);
          if ( x.getElementsByClassName('entry_times-wrapper').length === 1 ) {
            var c = x.getElementsByClassName('entry_times-wrapper').length === 1;
          x.style.display = 'none';
          }
        }
    });
}

HTML结构:

<div class="single-entry" id="9127">
   <div class="entries_wrapper">
      <div class="entry_times-wrapper">
        <!-- this is where the <a> tags is. -->
      </div>
    </div>
</div>

我们有一个带有 class 的 HTML 标签single-entry。此类存在多次,但每个都指定了唯一的 ID。名为的类名entry_times-wrapper(它是 variable 的子元素X)也有多个<a>标签。

我们想要做的:如果类中的所有项目entry_times-wrapper都被隐藏(使用 display none),则single-entry仅隐藏该特定 ID 的类。目前,上述代码实际上将隐藏所有这些单个条目。

我们怎样才能正确地做到这一点?

标签: javascriptjqueryshow-hide

解决方案


这是一个带有几个<div>s 和<a>s 的工作演示:

$("button").click(function(){ $(".single-entry").add("a").show();});
$(".entry_times-wrapper a").click(function(){ $(this).hide();checkVis();})

// this needs to be called every time an <a> element is hidden or made visible again:
function checkVis(){
  $(".single-entry").each(function(){
    $(this).toggle($(".entry_times-wrapper a:visible",this).length>0)
  });
}
.single-entry {background-color:#ccc; padding:6px;
               border: 1px black solid; margin: 4px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>show all links again</button><br>
<div class="single-entry" id="9127">
   <div class="entries_wrapper">
      <div class="entry_times-wrapper">
        <a href="#">first link<br></a>
        <a href="#">second link<br></a>
        <a href="#">third link</a>
      </div>
    </div>
</div>
<div class="single-entry" id="9128">
   <div class="entries_wrapper">
      <div class="entry_times-wrapper">
        <a href="#">fourth link<br></a>
        <a href="#">fifth link<br></a>
        <a href="#">sixth link</a>
      </div>
    </div>
</div>
<div class="single-entry" id="9129">
   <div class="entries_wrapper">
      <div class="entry_times-wrapper">
        <a href="#">seventh link<br></a>
        <a href="#">eighth link<br></a>
        <a href="#">ninth link</a>
      </div>
    </div>
</div>


推荐阅读