如果此div中的元素(span)为空,则不显示div

时间:2018-02-09 16:18:39

标签: javascript jquery html css

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



<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>
&#13;
&#13;
&#13;

在此示例中,我想在第一个display: none上设置div。我怎么能用jQuery做到这一点?

3 个答案:

答案 0 :(得分:0)

&#13;
&#13;
$(document).ready(function() {
  $('.mydiv').each(function() {
    var eleSpan = $(this).children().siblings("span");
    if (eleSpan.html().trim().length === 0) {
      $(this).hide();
    }
  });
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

迭代所有div的子节点,如果它们为空,则将parent(div)CSS显示变量设置为none。

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

答案 2 :(得分:-1)

请参阅内联注释,您永远不应该拥有重复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>