滑动手风琴与纯JS和for循环

Sliding accordion with pure JS and for loop

本文关键字:for 循环 JS 手风琴      更新时间:2023-09-26

我已经写了一个for循环,它应该贯穿所有手风琴和它们的子级,但是我不知道为什么它只在第一个对象上工作。

小提琴示例

for (
    var i = 0,
    accordion = document.getElementsByClassName('accordion');
    i < accordion.length;
    i++
) {
    var accordion_section = accordion[i].children[i],
        accordion_key = accordion[i].children[i].children[0],
        accordion_bellow = accordion[i].children[i].children[1];
    function accordion_bellow_MarginTop( value ) {
        accordion_bellow.style.marginTop = value + 'px';
    }
    accordion_bellow_MarginTop( -accordion_bellow.offsetHeight );
    accordion_key.onclick = function() {
        if ( accordion_section.getAttribute('class' ) == 'active' ) {
            accordion_section.setAttribute('class', '');
            accordion_bellow_MarginTop( -accordion_bellow.offsetHeight );
        }
        else {
            accordion_section.setAttribute('class', 'active');
            accordion_bellow_MarginTop( 0 );
        }
        return false;
    }
}

这里有几个问题在起作用。正如前面的评论者所指出的,您没有正确地循环手风琴中的每个部分。修复此问题后,您还需要解决 onClick 处理程序无法正常工作的事实。

遍历每个部分的问题在于您使用了不正确的变量范围。发生的情况是,只有您循环访问的最后一个元素会受到单击处理程序的影响。这是因为变量 "accordion_section" 和 "accordion_bellow" 将始终引用 main for 循环中的最后一组元素。

这与它们将成为循环期间分配的唯一元素的预期相反。这是因为变量 "accordion_section" 和 "accordion_bellow" 是在 onClick 函数的作用域之外定义的。为了使 onClick 正常工作,需要在 for 循环的每次迭代期间在单独的范围内定义这些变量。

为此,您可以使用如下所示的匿名函数:

for (var i = 0; i < sections.length; i++) 
{
    (function() {
        var section = sections.item(i),
            anchor = sections.item(i).children[0],
            below = sections.item(i).children[1];
        closeBelow(below, -below.offsetHeight);
        anchor.onclick = function () {
            if (section.getAttribute('class' ) == 'active' ) {
                section.setAttribute('class', '');
                closeBelow(below);
            }
            else {
                section.setAttribute('class', 'active');
                openBelow(below);
            }
        }
    })();
}

在此解决方案中,变量"部分"、"锚点"和"下面"始终特定于要循环的元素。通过使用自执行函数,可以确保每个单击处理程序仅适用于本地范围的变量。

解决方案:http://jsfiddle.net/b0u916p4/4/

你需要先在里面做另一个循环

通过这种方式,您可以获得所有手风琴和每个手风琴的所有部分

试试这个:

for (i = 0,
     accordion = document.getElementsByClassName('accordion');
    i < accordion.length;
    i++) {
    for (j = 0;
        j <= accordion[i].children.length;
        j++) {

              //your code here
     }
}