jQuery如何遍历多个同级元素

时间:2018-10-29 03:37:08

标签: javascript jquery loops next

我有一个jQuery项目,我必须遍历h2标头的列表,但是在每个h2标头中,我必须遍历它们的兄弟姐妹。每个标头具有1个以上的同级。现在,我只知道如何转到使用.next()函数的同级对象。有人可以在不更改初始代码方向的情况下帮助我浏览同级列表。

<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>

1 个答案:

答案 0 :(得分:1)

您可以使用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>