【问题标题】:hide an element if one of the siblings is empty如果其中一个兄弟元素为空,则隐藏元素
【发布时间】:2012-03-28 18:26:18
【问题描述】:

如果 div 'name' 为空,我需要隐藏 div 'email' 内容。我这样做了:

$(document).ready(function() {
    $('.media-contact').each(function() { 
        if ($(this).children('.name').text()===''){
         $(this).children('.email').hide();
        }
    }

});

但这不起作用。会有多个这样的媒体联系人,并不是所有的名字 div 都会被一个值填充,所以只有静态文本“Email”会显示出来,让它变得丑陋。我想遍历每个媒体联系人并检查“姓名”是否为空,如果是,则隐藏“电子邮件”..请帮助..

<div class="media-contact">
        <div class="name">
            Bill Bero
        </div>
        <div class="title">
            Communications and Media Relations Specialist
        </div>
        <div class="email">
            <a class="rc-link" href='mailto:will.kero@canalliance.org'><span><img src="/sites/dev/style%20library/images/design/icons/icon_email.png" alt=""/><em>EMAIL</em></span></a>
        </div>
        <div class="phone">
            <span class="baec5a81-e4d6-4674-97f3-e9220f0136c1" style="white-space: nowrap">
            219-661-3099, ext. 2
            </span>
        </div>
    </div>

【问题讨论】:

  • 我不知道这是你的完整代码还是什么,但你在...text()==='' 之后缺少一个结束) 所以它应该是...text()===''){
  • 修复了,还是不行..

标签: jquery hide children


【解决方案1】:

试试这个:

$('.media-contact').each(function() {
    if ($.trim($(this).children('.name').text()) === '') {
        $(this).children('.email').hide();
    }
}​);​

看到这个jsFiddle example,其中一个名字存在而另一个名字不见了。

【讨论】:

    【解决方案2】:

    将 text() 与空字符串进行比较充其量是不确定的,并且可能在不同的浏览器中表现不同。检查 ":empty" 应该会更好,尽管取决于页面的呈现方式,可能仍然有一个带有换行符或其他内容的文本节点。

    $(document).ready(function() {
        $('.media-contact').each(function() { 
            if ($(this).children('.name').is(":empty")) {
             $(this).children('.email').hide();
            }
        }
    });
    

    【讨论】:

    • 这也不起作用..可以修剪 .name 的值修复它吗?
    • 你可以试试... $.trim($(this).children('.name').text()) == ""
    【解决方案3】:

    试试this:

    $(document).ready(function() {
        $('.media-contact').each(function() { 
            var $this = $(this);
            if ($this.find(".name").html().trim() == "") {
                $this.find(".email").hide();
            }
        }
    
    });
    

    【讨论】:

      【解决方案4】:

      这是一个想法。使用切换和布尔值。

      $(document).ready( function () {
          $('.media-contact').each( function () {
              $(this).find('.email')
                  .toggle( $.trim( $(this).find('.name').text() ) !== '' );
          });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-26
        • 2016-08-09
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-15
        • 1970-01-01
        相关资源
        最近更新 更多