简体   繁体   English

DIV“sec2”为空时隐藏“btn 2”

[英]Hide "btn 2" when DIV "sec2" is empty

my code is working fine, but I would like to make a change where I didn't find answers just by searching.我的代码运行良好,但我想进行更改,仅通过搜索无法找到答案。 I'm looking for dynamic data for the sections below, but when I don't have data to populate, I'd like to hide the button, is that possible?我正在寻找以下部分的动态数据,但是当我没有要填充的数据时,我想隐藏按钮,这可能吗?

<style>
.elementor-editor-active .hidden{
display:block;
}
.hidden{
display: none;    
}
.shown{
display: block !important;
}
</style>
<script>
var btn1 = document.getElementById("btn1"); 
var btn2 = document.getElementById("btn2");
var btn3 = document.getElementById("btn3");
var btn4 = document.getElementById("btn4");


btn1.onclick = function(event){
event.preventDefault();
toggleDivs("sect1"); 
};
btn2.onclick = function(event){
event.preventDefault();
toggleDivs("sect2");
};
btn3.onclick = function(event){
event.preventDefault();
toggleDivs("sect3");
};
btn4.onclick = function(event){
event.preventDefault();
toggleDivs("sect4");
};


function toggleDivs(s){

document.getElementById("sect1").classList.remove("shown");
document.getElementById("sect2").classList.remove("shown");
document.getElementById("sect3").classList.remove("shown");
document.getElementById("sect4").classList.remove("shown");

document.getElementById(s).classList.add("shown");
}
btn1.focus(); 
btn1.click(); 
</script>

I dont see your HTML tree, so I can't really give an accurate answer.我没有看到您的 HTML 树,所以我无法给出准确的答案。 But you can use mutationObserver, so you can observe your target element.但是你可以使用mutationObserver,所以你可以观察你的目标元素。 If there is no data you can run a function to hide buttons.如果没有数据,您可以运行 function 来隐藏按钮。

Here is a snippet that will hide a button if the associated div is empty:这是一个片段,如果相关的 div 为空,它将隐藏一个按钮:

 const divs=document.querySelectorAll("div"), hideAll=()=>divs.forEach(d=>{ // hide all selected divs if (d.textContent==="") // hide associated button too, if div is empty: document.getElementById(d.id.replace("sect","btn")).style.display="none" d.style.display="none" }); document.onclick=ev=>{ if(ev.target.tagName==="BUTTON") { if (ev.target.id){ hideAll(); document.getElementById(ev.target.id.replace("btn","sect")).style.display="" } else { divs[2].textContent=""; hideAll() } }} hideAll();
 div {background-color:#ddd; padding:10px; margin:6px; border: 1px solid grey}
 <div id="sect1">This is section one</div> <div id="sect2">This is section two</div> <div id="sect3">This is section three</div> <div id="sect4">This is section four</div> <button id="btn1">show one</button> <button id="btn2">show two</button> <button id="btn3">show three</button> <button id="btn4">show four</button> <br><br> <button>empty div#sect3</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM