Jquery - 如何在表之前隐藏h2和表后的文本
Jquery - How to hide h2 before table and text after table?
我正在我的网站上工作,我不知道如何在表格之前隐藏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/
如果可以用span
或div
包装该#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 元素
相关文章:
- 如何使用jquery在填充自动完成的值后使文本框只读
- 使用Clipboard.js复制span文本
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 用程序搜索JQuery数据表中的文本
- jQuery匹配JSON对象的部分文本
- onkeyup无法动态创建多个文本区域
- 如何在下面的ES6循环中获得前面的文本
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 让文本输入幻灯片显示输入时的新文本输入?然后向后滑动
- 借助asp.net验证或java脚本对多个文本进行验证
- 无法在ajaxStart中更改跨度文本
- 高亮显示时编辑文本大小和颜色
- jquery中的文本框验证
- Javascript,有没有一种方法可以将数组写成没有逗号或空格的单个文本字符串
- 更改 H2 上联系表单的文本
- Jquery - 如何在表之前隐藏h2和表后的文本
- 从Web应用程序网页的HTML元素(h2/span)中获取数据(文本)
- 集& lt; h2>文本基于表格单元格- jQuery
- jQuery -选择所有文本"下面"h1或h2
- jQuery Onclick事件在特定h2包含特定文本