jQuery 如何遍历超过 1 个兄弟元素

jQuery how to loop through more than 1 sibling element

我有一个 jQuery 项目,我必须在其中循环遍历 h2 header 的列表,但在每个 h2 header 中我必须遍历他们的兄弟姐妹。每个 header 都有超过 1 个兄弟姐妹。现在我只知道如何转到使用 .next() 函数的 1 个同级。有人可以帮我在不改变初始代码方向的情况下遍历兄弟姐妹列表吗?

<script>
// Code Option 1
    function putSiblingsInTableForEachH2() {
        // line above sets function that will ultimately store siblings of each h2.toggler into a HTML table
        var siblingsGoInTable = [];
        // line creates empty array that will hold elements that will eventually go into HTML table
        var togglerHeaders = $("h2.toggler");
        // line above sets variable togglerHeaders to all h2 elements with a class of ".toggler"
        for (i = 0; i < togglerHeaders.length; i++) {
            // line above is a for loop that loops through variable togglerHeaders (for its entire length)
            var currentH2Element = togglerHeaders[i];
            // line above sets variable currentH2Element to togglerHeaders at position i
            // so when i starts at 0 currentH2Element is set to the first element in togglerHeaders which is the first h2.toggler
            for (j = 0; j < currentH2Element.nextAll(); j++) {
                if (currentH2Element.nextAll() !== currentH2Element.val()) {
                    $(siblingsGoInTable).wrapAll("<table></table>");
                } // line ends if statement
            } // line above closes for loop 
        } // line ends for loop
    } // line ends function
    putSiblingsInTableForEachH2();
    // line above actually runs function
</script>

您可以使用 the .siblings() method 来实现此目的。

因此,以下内容可能对您有用:

<script>
    function putSiblingsInTableForEachH2() {
        var siblingsGoInTable = [];

        var togglerHeaders = $("h2.toggler");

        for (var i = 0; i < togglerHeaders.length; i++) {

            var currentH2Element = togglerHeaders[i];

            // Access siblings like this
            var siblings = $(currentH2Element).siblings();

            for (var j = 0; j < siblings.length; j++) {

                var siblingToH2 = siblings[j];
                // Do what you need to do with sibling element here
            }
        }
    }

    putSiblingsInTableForEachH2();

</script>