为空

时间:2018-01-15 11:14:52

标签: jquery

我试图隐藏元素的父级,如果它是空的。我正在列出工作时间。我每天都有7个领域。但是如果你想在星期一到星期五制作一个项目,我想让其他4个字段禁用。

此刻我得到了这个:

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

  if (isEmpty($('p .spanItem')) && isEmpty($('p .spanEnd'))) {
       $(".spanItem").parent().hide();

这会禁用父级,但也禁用其他父级,这意味着它根本不显示列表。

此外,如果第一个元素中包含内容,则即使其他元素为空,也会忽略该函数。

<p><?php echo $row['day_one']?>:         <span class="spanItem"><?php echo $row['day_one_starttime'] ?></span>          <span class="spanEnd"><?php echo $row['day_one_closing'] ?></p>
<p><?php echo $row['day_two']?>:         <span class="spanItem"><?php echo $row['day_two_starttime'] ?></span>          <span class="spanEnd"><?php echo $row['day_two_closing'] ?></p>
<p><?php echo $row['day_three']?>:       <span class="spanItem"><?php echo $row['day_three_starttime'] ?></span>        <span class="spanEnd"><?php echo $row['day_three_closing'] ?></p>
<p><?php echo $row['day_four']?>:        <span class="spanItem"><?php echo $row['day_four_starttime'] ?></span>         <span class="spanEnd"><?php echo $row['day_four_closing'] ?></p>
<p><?php echo $row['day_five']?>:        <span class="spanItem"><?php echo $row['day_five_starttime'] ?></span>         <span class="spanEnd"><?php echo $row['day_five_closing'] ?></p>
<p><?php echo $row['day_six']?>:         <span class="spanItem"><?php echo $row['day_six_starttime'] ?></span>      <span class="spanEnd"><?php echo $row['day_six_closing'] ?></p>
<p><?php echo $row['day_seven']?>:       <span class="spanItem"><?php echo $row['day_seven_starttime'] ?></span>        <span class="spanEnd"><?php echo $row['day_seven_closing'] ?></p>

用$(this)看过很多例子,但它们都是点击功能。我尝试使用$(this),但它没有用。

我可以为每个

添加一个类并调用该类,但这会使我的代码变得不必要。

1 个答案:

答案 0 :(得分:0)

问题是因为您一次检查所有.spanItem个元素。您需要循环遍历它们并单独检查每个:

$('p').each(function() {
  var text = $(this).find('.spanItem').text().trim() + $(this).find('.spanEnd').text().trim();
  $(this).toggle(text.trim() !== '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  Day one:
  <span class="spanItem">Day one start</span> 
  <span class="spanEnd">Day one closing</span>
</p>
<p>
  Day two: <!-- this will be hidden --> 
  <span class="spanItem"></span> 
  <span class="spanEnd"></span>
</p>
<p>
  Day three:
  <span class="spanItem"></span> 
  <span class="spanEnd">Day three closing</span>
</p>
<p>
  Day four: <!-- this will be hidden --> 
  <span class="spanItem"></span> 
  <span class="spanEnd"></span>
</p>
<p>
  Day five:
  <span class="spanItem">Day five start</span> 
  <span class="spanEnd"></span>
</p>
<p>
  Day six: <!-- this will be hidden --> 
  <span class="spanItem"></span> 
  <span class="spanEnd"></span>
</p>
<p>
  Day seven:
  <span class="spanItem">Day seven start</span> 
  <span class="spanEnd">Day seven closing</span>
</p>

我通过检查text()是否为空来简化逻辑,并根据需要使用toggle()隐藏/显示父级。另请注意,您在HTML中遗漏了一些</span>个标记。