Jquery - 如何在表之前隐藏h2和表后的文本

Jquery - How to hide h2 before table and text after table?

本文关键字:h2 文本 隐藏 Jquery      更新时间:2023-09-26

我正在我的网站上工作,我不知道如何在表格之前隐藏h2标签,在表格之后隐藏文本。你可以帮我吗?非常感谢您的帮助。

.HTML:

<h2>
  <a class="h2 dark" href="/be/ae/3_controls-training.html" name="3">Controls Training</a>
</h2>
<table class="training" cellspacing="0" width="100%" style="display: none;">
 <tbody>
   <tr>
     <th style="text-align: left;">Training</th>
     <th style="text-align: left;">Start</th>
     <th style="text-align: left;">End</th>
     <th style="text-align: left;">Location</th>
     <th style="text-align: right;">Price*</th>
     <th> </th>
   </tr>
 </tbody>
</table>
)* EUR excl. BTW

JQuery:

<script type="text/javascript">
$(document).ready(function() {
    // this is code for hiding my table if td is not inside
    $('.training').each(function(){
       if ($(this).find('td').length == 0){
        $(this).closest('h2').hide(); // I try to hide h2 before table without success
        $(this).hide(); // this works fine
        // I don't know how to hide text after table
       }
    });
});
</script>

要在 DOM 中获取前一个元素,您可以使用 jQuery .prev() http://api.jquery.com/prev/

$(this).prev().hide();

您无法选择文本,因为它不是 DOM 元素。将其包装在 p 标签中,然后您可以使用 .next() http://api.jquery.com/next/

$(this).next().hide();

示例:http://jsfiddle.net/sfctbnkz/

如果可以用spandiv包装该#text,这很容易。然后,您可以使用.prev.next来选择表前后的元素。

万一,如果您无法访问标记......那么唯一的方法是获取内容并查找文本并将其删除。

请参阅下面的演示..它不会显示任何内容。因为 OP 的输出是删除/隐藏所有内容。:)

注意:下面的代码删除了表后面的下一个文本节点..所以正确测试它并根据需要进行更改。

$('.training').each(function() {
  $(this).prev('h2').remove(); //remove or hide h2
  var tableSiblings = $(this).parent().contents();
  var deleteNext = false;
  $.each(tableSiblings, function(i, content) {
    if (deleteNext) {
      $(this).remove();
      deleteNext = false;
    }
    if ($(this).hasClass('training')) {
      deleteNext = true;
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>
  <a class="h2 dark" href="/be/ae/3_controls-training.html" name="3">Controls Training</a>
</h2>
<table class="training" cellspacing="0" width="100%" style="display: none;">
  <tbody>
    <tr>
      <th style="text-align: left;">Training</th>
      <th style="text-align: left;">Start</th>
      <th style="text-align: left;">End</th>
      <th style="text-align: left;">Location</th>
      <th style="text-align: right;">Price*</th>
      <th></th>
    </tr>
  </tbody>
</table>
)* EUR excl. BTW

试试这个

$('.training').closest( 'h2' ).hide(); // will hide closest h2 tag, but could be after
$('.training').next().hide(); // will hide element directly after .training

您应该尝试添加特定于您尝试执行的操作的类,而不是依赖 dom 元素