我正在创建一个包含问题和解释的常见问题列表。默认情况下,我只想显示问题。
如果用户点击某个特定问题,则只应展开其答案,关闭所有其他答案。
我正在使用嵌套循环。
<html>
<head>
<title></title>
</head>
<script>
function display(k){
for(i=1;i<=k;i++){
for(j=i; j<=i; j++){
document.getElementById('sol'+j).style.display="block";
}
document.getElementById('sol'+i).style.display="none";
}
}
</script>
<body>
<div id="faq1" onclick="display(1)">FAQ 1: Return Policy
<div id="sol1" style="display: none;">
Customer can replace products within 30 days from the days of purchase.
</div>
</div>
<div id="faq2" onclick="display(2)">FAQ 2: Warranty
<div id="sol2" style="display: none;">
Warranty would be solely fulfiled by the brand company.
</div>
</div>
<div id="faq3" onclick="display(3)">FAQ 3: Extended Warranty
<div id="sol3" style="display: none;">
Customer can apply for extended warranty for their products provided their products fulfil the TOS.
</div>
</div>
<div id="faq4" onclick="display(4)">FAQ 4: Address
<div id="sol4" style="display: none;">
Our company is situated in the heart of the city Jammu.
</div>
</div>
</body>
</html>
我尝试了不同的组合,但我被卡住了。
答案 0 :(得分:1)
更简单的方法是为所有问题和所有答案添加CSS类。
然后指定让我们使用.answer
,隐藏类元素(.answer {display: none}
)。然后,使用JS为所有问题类元素创建一个事件监听器,并在单击时切换它的子div(.answer)。
这样,您可以避免在代码中出现许多错误和糟糕的设计选择,例如:重复的ID,内联样式,每个问题div的单独onclick属性等。
答案 1 :(得分:1)
添加jquery并使其变得简单。
<script type="text/javascript">
$(document).ready(function(){
$('.faq').click(function(){
if($(this).find('div:first-child').is(':visible'))
$(this).find('div:first-child').hide('slow');
else
{
$('.faq').children().hide('slow');
$(this).find('div:first-child').show('slow');
}
});
});
</script>
答案 2 :(得分:0)
HTML就在这里
<div id="faq1" class="faqcls">FAQ 1: Return Policy
<div id="sol1" class="solcls" style="display: none;">
Customer can replace products within 30 days from the days of purchase.
</div>
</div>
<div id="faq2" class="faqcls" >FAQ 2: Warranty
<div id="sol2" class="solcls" style="display: none;">
Warranty would be solely fulfiled by the brand company.
</div>
</div>
<div id="faq3" class="solcls" class="faqcls">FAQ 3: Extended Warranty
<div id="sol3" style="display: none;">
Customer can apply for extended warranty for their products provided their products fulfil the TOS.
</div>
</div>
<div id="faq4" class="solcls" class="faqcls">FAQ 4: Address
<div id="sol4" style="display: none;">
Our company is situated in the heart of the city Jammu.
</div>
</div>
和javascript在这里
$(document).on('click','.faqcls',function() {
$(this).find('.solcls').slideToggle();
});
和jsfiddle是http://jsfiddle.net/A3Pwg/
答案 3 :(得分:0)
尝试使用document.getElementsByClassName
:请参阅 DEMO
function display(k){
arr = document.getElementsByClassName('sol');
for(i=0; i<arr.length; i++){
arr[i].style.display="none";
}
document.getElementById('sol'+k).style.display="block";
}
的CSS:
.sol{
display: none;
}
并将等级sol
添加到div:
<div id="sol1" class="sol">
Customer can replace products within 30 days from the days of purchase.
</div>