【问题标题】:Display none a div if a element (span) inside this div is empty如果此 div 内的元素(跨度)为空,则不显示 div
【发布时间】:2018-07-20 11:15:47
【问题描述】:

如果此 div 中的 span 元素为空,我想在 div 上设置 display: none

<div class="mydiv test1">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/30/Googlelogo.png/1200px-Googlelogo.png" width="100px">
  <span id="myid"></span>
</div>
<div class="mydiv test2">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/30/Googlelogo.png/1200px-Googlelogo.png" width="100px">
  <span id="myid">100</span>
</div>

在这个例子中,我想在第一个div 上设置display: none。如何使用 jQuery 做到这一点?

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

$(document).ready(function() {
  $('.mydiv').each(function() {
    var eleSpan = $(this).children().siblings("span");
    if (eleSpan.html().trim().length === 0) {
      $(this).hide();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv test1">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/30/Googlelogo.png/1200px-Googlelogo.png" width="100px">
  <span id="myid"></span>
</div>
<div class="mydiv test2">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/30/Googlelogo.png/1200px-Googlelogo.png" width="100px">
  <span id="myid">100</span>
</div>

【讨论】:

    【解决方案2】:

    遍历所有作为 div 子元素的 span,如果它们为空,则将父 (div) CSS 显示变量设置为 none。

    $.each($('div > span'), function(index) {
      if($(this).is(':empty')) {
        $(this).parent().css('display', 'none');
      }
    });
    

    【讨论】:

      【解决方案3】:

      查看 cmets inline 并且您永远不应该有具有重复 id 值的元素。

      // Get all the span elements into an array
      var spans = Array.prototype.slice.call(document.querySelectorAll("span"));
      
      // Loop over the span elements
      spans.forEach(function(span){
        // Check to see if there is any text content
        if(span.textContent === ""){
           span.parentElement.classList.add("hidden");  // Hide the parent
        }
      });
      .hidden { display:none; }
      <div class="mydiv test1">
        <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/30/Googlelogo.png/1200px-Googlelogo.png" width="100px">
        <span id="mySpan1"></span>
      </div>
      
      <div class="mydiv test2">
        <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/30/Googlelogo.png/1200px-Googlelogo.png" width="100px">
        <span id="mySpan2">100</span>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-30
        • 2012-01-08
        • 2015-02-19
        相关资源
        最近更新 更多