一次显示一个常见问题,隐藏其他的

JS - Show one FAQ at a time, hide others

本文关键字:隐藏 其他 常见问题 一次 显示 一个      更新时间:2023-09-26

常见问题

JS代码:

var $ = function (id) {
return document.getElementById(id);
};
var faqs = $("faqs");
var h2Elements = faqs.getElementsByTagName("h2");
var h2Node;
for (var i = 0; i < h2Elements.length; i++) {
    h2Node = h2Elements[i];

}
$("first_link").focus();
$(document).ready(function () {
    $("h2").click(function () {
        if (h2.hasAttribute("class")) {
            h2.removeAttribute("class");
        } else {
            h2.setAttribute("class", "minus");
        }
        if (h2.nextElementSibling.hasAttribute("class")) {
            h2.nextElementSibling.removeAttribute("class");
        } else {
            h2.nextElementSibling.hide();
        }
    });
});

在点击一个问题时,应该显示答案。当我点击一个不同的问题,所有其他的答案应该撤回(隐藏)。我调整了几次,要么代码不会隐藏任何东西(所有的答案仍然打开),要么所有的答案都不会打开。

从$(document)开始。ready(function(){,我如何得到的问题打开一个在一次点击(关闭其他)?

任何输入将不胜感激!

创建一个函数来隐藏所有其他具有类名opendiv,如:

function hideOthers() {
    var othersDivEle = document.getElementsByClassName("open");
    for(var d = 0; d < othersDivEle.length; d++) {
        othersDivEle[d].removeAttribute("class");
    }
}

并将代码更改为:

...
} else {
   hideOthers();
   h2.nextElementSibling.setAttribute("class", "open");
}

..
} else {
    hideOthers();            
    h2.nextElementSibling.setAttribute("class", "open");
}
更新jsFiddle