当谈到javascript时,我是一个完全的初学者,我正在尝试创建一个简单的if/else语句,以显示不同的div。
我需要根据两个div文本通过javascript显示div:
例如,如果div.delivery.p.stado1是";关闭";并且div.online.p.stado2是";关闭";插入div:<div class "hello-world">onaire</div>
如果div.deliver.p.estado1是";在"on"上;,并且div.online.p.stado2是";关闭";什么都不显示。
如果div.deliver.p.estado1是";"关";,并且div.online.p.stado2是";关于";什么都不显示。
案例1:
<div class = "delivery"> <p class = "status1"> off </p></div>
<div class = "online"> <p class = "estado2"> off </p></div>
案例2:
<div class = "delivery"> <p class = "status1"> on </p></div>
<div class = "online"> <p class = "estado2"> on </p></div>
我应该使用queryselector,但我仍然不确定如何
任何帮助都会得到的大力支持
试试这个
let p1 = document.querySelector('.status1').textContent;
let p2 = document.querySelector('.estado2').textContent;
if(p1 == 'off' && p2 == 'off'){
var seccion = document.querySelector("#miseccion");
var parrafo = document.createElement("p");
parrafo.className = "hello-world";
var texto = document.createTextNode("onair");
parrafo.append(texto);
seccion.append(parrafo);
}
<div class = "delivery">
<p class = "status1">off</p>
</div>
<section id="miseccion">
</section>
<div class = "online">
<p class = "estado2">off</p>
</div>
我只需要使用两组div,并显示所需的对,隐藏另一对。
function myFunction(isOn) {
var deliveryOn = document.getElementById("delivery-on");
var onlineOn = document.getElementById("online-on");
var deliveryOff = document.getElementById("delivery-off");
var onlineOff = document.getElementById("online-off");
if(isOn){
deliveryOn.style.display = "block";//use block, inline, or inline-block depending on your needs
onlineOn.style.display = "block";
deliveryOff.style.display = "none";
onlineOff.style.display = "none";
}
else{
deliveryOff.style.display = "block";//use block, inline, or inline-block depending on your needs
onlineOff.style.display = "block";
deliveryOn.style.display = "none";
onlineOn.style.display = "none";
}
}
.delivery{
//css here
}
.online{
//css here
}
.on{
//css here
}
.off{
//css here
}
<div class = "delivery" id="delivery-off"> <p class = "status1"> off </p></div>
<div class = "online" id="online-off"> <p class = "estado2"> off </p></div>
<div class = "delivery" id="delivery-on"> <p class = "status1"> on </p></div>
<div class = "online" id="online-on"> <p class = "estado2"> on </p></div>
我承认我不是专业人士,所以我的代码可能有缺陷。
较小版本的
let firstStatus = document.querySelector('.status1').innerText;
let secondStatus = document.querySelector('.status2').innerText;
let onaire = document.querySelector('.onaire');
if (firstStatus === 'off' && secondStatus === 'off'){
let textEl = document.createTextNode('onaire')
onaire.append(textEl)
}else{
onaire.style.display = 'none';
}
<div class="delivery">
<p class="status1"> off </p>
</div>
<div class="online">
<p class="status2"> off </p>
</div>
<div class="onaire"></div>