【问题标题】:Hide a div if content is empty如果内容为空,则隐藏 div
【发布时间】:2012-01-08 23:34:30
【问题描述】:

哲学气泡就像一个引用/演讲气泡样式的 div,里面有一个共享点控件,richHtmlField 允许用户在编辑页面时输入内容,但是如果用户选择将其留空,则不会有内容div 所以只有气泡会出现在页面中,这看起来很有趣,所以我想在没有用户输入或基本上 div 为空时隐藏整个 div?你是如何在 jquery 中做到这一点的?

<div class="philosophy-bubble">
<PublishingWebControls:RichHtmlField FieldName="carephilosophy" runat="server"></PublishingWebControls:RichHtmlField>
</div>  

【问题讨论】:

    标签: javascript jquery html hide


    【解决方案1】:
    var myDiv =  $('#myDiv');
    
    if (myDiv.text() == '')
    {
        myDiv.hide();
    }
    

    【讨论】:

      【解决方案2】:

      使用 jQuery 的 :empty 选择器:

      $('.philosophy-bubble:empty').hide();
      

      这里是a working fiddle

      替代方案

      您还可以使用filter() 函数查找所有空的 div 并隐藏:

      //All divs
      $('div').filter(function() {
              return $.trim($(this).text()) === ''
      }).hide()
      
      //div's with a certain class
      $('.philosophy-bubble').filter(function() {
              return $.trim($(this).text()) === ''
      }).hide()
      
      //div with a specific ID
      $('#YourDivID').filter(function() {
              return $.trim($(this).text()) === ''
      }).hide()
      

      ..等等

      注意::empty 选择器会更高效。 See jsPerf.

      【讨论】:

      【解决方案3】:

      类似:

      if ($('.philosophy-bubble').is(":empty")){
          $('.philosophy-bubble').hide();
      }
      

      这是一个小提琴:http://jsfiddle.net/IrvinDominin/XYr9T/1/

      编辑

      更好地使用:

      $('.philosophy-bubble:empty').hide()
      

      http://jsfiddle.net/IrvinDominin/XYr9T/3/

      【讨论】:

        猜你喜欢
        • 2021-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-30
        • 2013-04-27
        • 2014-02-27
        相关资源
        最近更新 更多