所以我有一个简单的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);
}
}
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 >
然而,在我点击后4秒钟,div就不会显示了。
我的代码有问题吗?
有人能进一步引导我吗?
非常感谢!
vara
是数组,因此需要为数组的所有元素设置样式。
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是一个数组。它没有样式属性。您必须对数组进行迭代,并更改每个数组的显示属性。
function myfunction() {
var a = document.querySelectorAll("p") ;
a.forEach( div => {
if(div.style.display == "none"){
setTimeout(function() {
div.style.display = "block";
}, 4000);
}
});
}