简体   繁体   English

如何设置超时以在Javascript中使用if函数显示多个div

[英]How to Settimeout to display multiple divs with if function in Javascript

So I have a simple javascript that looks like this所以我有一个简单的javascript,看起来像这样

function  myfunction(){

var a = [document.getElementById("div1"),
document.getElementById("div2"), document.getElementById("div3")];

if(a.style.display=="none"){

setTimeout(function(){a.style.display="block";},4000);
}

}

And html code looks like this和 html 代码看起来像这样

<  a href="#" onclick="myfunction();"  >   click to show div1 and div2 after 4 seconds<   /a  >

<  p id="div1"   style="display:none;" >divv1<  /p  >


<  p id="div2"    style="display:none;"    >divv2<  /p  >



<  p id="div3"    style="display:none;"    >divv3<  /p  >

However divs are not showing after 4 seconds after I clicked.但是,我点击 4 秒后 div 没有显示。

Is there something wrong with my code?我的代码有问题吗?

Can someone please guide me further?有人可以进一步指导我吗?

Thanks alot!非常感谢!

var a is the array, so you need to set the style for all the elements of the array. var a是数组,因此您需要为数组的所有元素设置样式。

 function myfunction() { var a = [document.getElementById("div1"), document.getElementById("div2"), document.getElementById("div3") ]; if (a[0].style.display == "none" && a[1].style.display == "none" && a[2].style.display == "none") { setTimeout(function() { a.forEach(item => item.style.display = "block"); }, 4000); } }
 <a href="#" onclick="myfunction();"> click to show div1 and div2 after 4 seconds </a> <p id="div1" style="display:none;">divv1 </p> <p id="div2" style="display:none;">divv2 </p> <p id="div3" style="display:none;">divv3 </p>

a is an array. a 是一个数组。 It does not have a style property.它没有样式属性。 You have to iterate over the array and change the display property for each.您必须遍历数组并更改每个数组的显示属性。

function  myfunction() {

  var a = document.querySelectorAll("p") ;

  a.forEach( div => {
    if(div.style.display == "none"){
      setTimeout(function() {
        div.style.display = "block";
      }, 4000);
    }
  });
}

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

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