7

我环顾四周,发现了很多关于此的问题,但没有一个解决方案对我有用。我有这样的结构:

<div class="pricetag">
    <div class="price">400</div>
</div>

<div class="pricetag">
    <div class="price"></div>
</div>

<div class="pricetag">
    <div class="price">250</div>
</div>

我想要做的是隐藏 .pricetag ,其中 .price 不包含任何内容。同一页面上可能有很多不同的 .pricetag,但我只想隐藏 .price 为空的那些。

jQuery可以做到这一点吗?我尝试了很多不同的脚本,但没有一个能正常工作。

4

6 回答 6

19

您可以使用:empty选择器和parent方法,假设空.price元素永远不会包含任何文本节点(例如换行符):

$(".price:empty").parent().hide();

这是一个工作示例

于 2012-07-02T08:50:31.723 回答
1

试试这个 jQuery 脚本

$(document).ready(function(e)
{
    $('div.pricetag').each(function(key, value)
    {
        if(!$('div.price', value).html()) $(value).hide();
    });
});
于 2012-07-02T09:03:11.137 回答
1
$('.price').each(function(){
  if ($(this).text().length == 0) {
    $(this).parent().hide()
  }
})
于 2012-07-02T08:49:39.880 回答
1

工作演示 http://jsfiddle.net/mm4pX/1/

您可以使用.is(':empty')检查 div 是否为空,然后隐藏父 div。

希望这可以帮助,

代码

$('.price').each(function() {
    if $('.price').is(':empty') $(this).parent().hide()
});​
于 2012-07-02T08:51:31.667 回答
1

这个 jquery 代码会做到这一点

$(function(){
  $(".price").each(function(){
    if($(this).html()=="")
      $(this).parent(".pricetag").hide();
  });
});

jsbin 示例:http: //jsbin.com/ovagus

于 2012-07-02T08:52:05.230 回答
1

如果:empty元素包含空格,则选择器不会选择该元素。如果这是一个问题,那么您可以从空格中修剪元素:

function isEmpty(element){
  return !$.trim(element.html())
}

$(".box").each(function() {
  var box = $(this);
  var body = box.find(".box-body");

  if(isEmpty(body)) {
    console.log("EMPTY");
    box.hide();
  } 
});

http://codepen.io/DanAndreasson/pen/jWpLgM

于 2016-02-02T08:38:06.047 回答