嘿,我的 for 循环只适用于第一个 div 的第一个元素,无论我点击什么 div 都会出错
<块引用>faq.js:14 未捕获的类型错误:无法读取未定义的属性“样式”。 我试图在循环之前声明 var div 或者我做了一个嵌套循环。
var i;
for (i = 0; i <= 3; i++) {
var p = document.getElementsByTagName('p')[i];
p.style.display = "none";
}
function Show() {
for (var j = 0; j < 4; j++){
var div = document.getElementsByClassName('faq-box')[j];
if(div.getElementsByTagName('p')[j].style.display == "none") {
div.getElementsByTagName('p')[j].style.display = "block";
}
else {
div.getElementsByTagName('p')[j].style.display = "none";
}
}
}
<h2>FAQ</h2>
<div class="faq-box">
<h4 onclick="Show()">How many team members can I invite?</h4>
<p>You can invite up to 2 additional users on the Free plan. There is no limit on
team members for the Premium plan.</p>
</div>
<hr>
<div class="faq-box">
<h4 onclick="Show()"> What is the maximum file upload size?</h4>
<p class="p">No more than 2GB. All files in your account must fit your allotted storage space.</p>
</div>
<hr>
<div class="faq-box">
<h4 onclick="Show()">How do I reset my password?</h4>
<p class="p">You can invite up to 2 additional users on the Free plan. There is no limit on
team members for the Premium plan.</p>
</div>
<hr>
答案 0 :(得分:0)
这里有一个解决方案,可以帮助您在没有硬编码的情况下朝着正确的方向工作!
for (let el of document.getElementsByTagName('p')) {
el.style.display = "none";
}
function Show(el) {
el = el.parentElement.getElementsByTagName("p")[0];
if (el.style.display == "none") {
el.style.display = "block";
} else {
el.style.display = "none";
}
}
<h2>FAQ</h2>
<div class="faq-box">
<h4 onclick="Show(this)">How many team members can I invite?</h4>
<p>You can invite up to 2 additional users on the Free plan. There is no limit on
team members for the Premium plan.</p>
</div>
<hr>
<div class="faq-box">
<h4 onclick="Show(this)"> What is the maximum file upload size?</h4>
<p class="p">No more than 2GB. All files in your account must fit your allotted storage space.</p>
</div>
<hr>
<div class="faq-box">
<h4 onclick="Show(this)">How do I reset my password?</h4>
<p class="p">You can invite up to 2 additional users on the Free plan. There is no limit on
team members for the Premium plan.</p>
</div>
<hr>