javascript - 使用 jQuery 和 JavaScript 隐藏特定元素
问题描述
我们的代码有问题:
function remove_single_entry_if_empty() {
$(".single-entry").each(function() {
var ids = $(this).attr('id');
let a = (ids);
for ( let i = 0; i < a.length; a++ ) {
let x = document.getElementById(a);
if ( x.getElementsByClassName('entry_times-wrapper').length === 1 ) {
var c = x.getElementsByClassName('entry_times-wrapper').length === 1;
x.style.display = 'none';
}
}
});
}
HTML结构:
<div class="single-entry" id="9127">
<div class="entries_wrapper">
<div class="entry_times-wrapper">
<!-- this is where the <a> tags is. -->
</div>
</div>
</div>
我们有一个带有 class 的 HTML 标签single-entry
。此类存在多次,但每个都指定了唯一的 ID。名为的类名entry_times-wrapper
(它是 variable 的子元素X
)也有多个<a>
标签。
我们想要做的:如果类中的所有项目entry_times-wrapper
都被隐藏(使用 display none
),则single-entry
仅隐藏该特定 ID 的类。目前,上述代码实际上将隐藏所有这些单个条目。
我们怎样才能正确地做到这一点?
解决方案
这是一个带有几个<div>
s 和<a>
s 的工作演示:
$("button").click(function(){ $(".single-entry").add("a").show();});
$(".entry_times-wrapper a").click(function(){ $(this).hide();checkVis();})
// this needs to be called every time an <a> element is hidden or made visible again:
function checkVis(){
$(".single-entry").each(function(){
$(this).toggle($(".entry_times-wrapper a:visible",this).length>0)
});
}
.single-entry {background-color:#ccc; padding:6px;
border: 1px black solid; margin: 4px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>show all links again</button><br>
<div class="single-entry" id="9127">
<div class="entries_wrapper">
<div class="entry_times-wrapper">
<a href="#">first link<br></a>
<a href="#">second link<br></a>
<a href="#">third link</a>
</div>
</div>
</div>
<div class="single-entry" id="9128">
<div class="entries_wrapper">
<div class="entry_times-wrapper">
<a href="#">fourth link<br></a>
<a href="#">fifth link<br></a>
<a href="#">sixth link</a>
</div>
</div>
</div>
<div class="single-entry" id="9129">
<div class="entries_wrapper">
<div class="entry_times-wrapper">
<a href="#">seventh link<br></a>
<a href="#">eighth link<br></a>
<a href="#">ninth link</a>
</div>
</div>
</div>
推荐阅读
- r - 按组对同一列进行管道操作
- huggingface-transformers - 如何使用拥抱面部转换器为翻译任务训练编码器-解码器模型?
- groovy - 通过 vars.putObject 将对象转换为“double”类
- javascript - 使用 ordeyByChild 在 Angular 中显示我的 firebase 数据的困难
- php - YouTube 配额用完了,我有什么选择?
- amazon-web-services - AWS SES 交付失败:将消息返回给发件人
- java - 带有gridview的recyclerview以不同的索引号重复项目两次
- c# - 在c#中提取Action方法参数
- arrays - MongoDB在嵌套数组中搜索
- python - 无法独立运行 docker compose 创建的图像