代码之家  ›  专栏  ›  技术社区  ›  Sammi

当其中一个p标记不为空时,隐藏另一个p标记

  •  -1
  • Sammi  · 技术社区  · 7 年前

    我有这样的结构 JSFiddle .

    我想做的是:当类(“折扣”)不为空时,其他3个p标记将被隐藏。当类别(“折扣”)为空时,将显示其他3个p标签。

    if($('.discount).is(':not("empty)'))
    

    .discount.innerHTML.length != 0
    

    3 回复  |  直到 5 年前
        1
  •  1
  •   charlietfl    7 年前

    可以按以下方式执行:

    $('.discount').not(':empty').parent().siblings().hide()
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h4>Info 1</h4>
    <div class="information">
      <p class="s">
        <em class="discount">DISCOUNT PROMOTION</em>
      </p>
      <p class="s">
        Title
      </p>
      <p class="s">
        Name
      </p>
      <p class="s">
        Detail
      </p>
      
    </div>
    
    <h4>Info 2</h4>
    <div class="information">
      <p class="s">
        <em class="discount"></em>
      </p>
      <p class="s">
        Title
      </p>
      <p class="s">
        Name
      </p>
      <p class="s">
        Detail
      </p>
      
    </div>
    
    <h4>Info 3</h4>
    <div class="information">
      <p class="s">
        <em class="discount">DISCOUNT PROMOTION</em>
      </p>
      <p class="s">
        Title
      </p>
      <p class="s">
        Name
      </p>
      <p class="s">
        Detail
      </p>
      
    </div>
        2
  •  0
  •   Shiladitya    7 年前

    给你一个解决方案 https://jsfiddle.net/0fy0kpc0/1/

    $(function(){
      if($('.discount').html().length){
       console.log("yeah!")
       $('.information p:nth-child(2)').hide();
       $('.information p:nth-child(3)').hide();
       $('.information p:nth-child(4)').hide();
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="information">
      <p class="s">
        <em class="discount">DISCOUNT PROMOTION</em>
      </p>
      <p class="s">
        Title
      </p>
      <p class="s">
        Name
      </p>
      <p class="s">
        Detail
      </p>
      
    </div>

    错误发生在 .discount.innerHTML.length != 0 JSFIDLE中的行

    给你另一个解决方案 https://jsfiddle.net/0fy0kpc0/2/

    $(function(){
      if (!$('.discount').is(':empty')){
        console.log("yeah!")
        $('.information p:nth-child(2)').hide();
        $('.information p:nth-child(3)').hide();
        $('.information p:nth-child(4)').hide();
      }
    });
    <脚本src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“>lt;/script>
    <div class=“信息”>
    <em class=“折扣”>折扣促销</em>
    </p>
    <p class=“s”>
    标题
    </p>
    <p class=“s”>
    名称
    </p>
    细节
    </p>
    
    </div>

        3
  •  0
  •   A.D.    7 年前

    尝试使用 :not() :has() 选择器:

    $(function(){
    
     if($('.discount').text().length != 0)
     {
    
       $("p:not(:has(>em))").hide();
        }
    });