gpt4 book ai didi

javascript - 如何创建按 parent /子女数量排序的数组?

转载 作者:行者123 更新时间:2023-11-29 10:15:10 26 4
gpt4 key购买 nike

如何让 javascript(或 jquery,如果它更容易)返回一个数组,从具有最少父元素的元素开始,然后是第二少、第三少……等等

所以像下面这样的 DOM

<div class="first">
<div class="second">
<div class="third"></div>
<div class="fourth">
<div class="fifth"></div>
</div>
</div>
<div class="sixth"></div>
<div class="seventh">
<div class="eighth"></div>
</div>
<div class="ninth"></div>
</div>
<div class="tenth"></div>

会返回这样的数组...

["first", "tenth", "second", "sixth", "seventh", "ninth", "third", "fourth", "eighth", "fifth"]

最佳答案

这个有效:

var $first = $('body').children('div'),          // Finds the first level
output = []; // Stores the results

while ($first.length != 0) { // While we still can go deeper
output = $.merge(output, assemble($first)); // Get the classes on this level
$first = $first.children('div'); // Dive deeper
}

console.log(output); // Output the results

function assemble(l) { // Collects classes at a level
var arr = [];
$.each(l, function() {
arr.push($(this).attr('class'));
});
return arr;
}

DEMO

关于javascript - 如何创建按 parent /子女数量排序的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23666009/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com