我想通过使用Javascript / jQuery遍历DOM来准备嵌套数组。感兴趣的元素位于#container
元素中,或者具有dot
类,或者是input
元素。
我想准备像[name,name1,[name2]]
这样的数组。我在这里使用了最常用的技术,例如递归。但是我无法使它起作用:
$(document).ready(function(){
var arr = [];
function recurse(parent, arr){
var temp = [];
parent.find('*').each(function(){
if($(this).is('input')){
if($(this).parents('.dot').length==1){
console.log($(this));
temp.push($(this).attr('id'))
}
}
if($(this).is('.dot')){
recurse($(this), arr);
}
});
arr.push(temp);
return arr;
}
var elm = $('#container').find('.dot:first');
console.log(recurse(elm, arr));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div class="dot">
<div class="dot">
<input type="password" id="name2" name="name2">
</div>
<input type="text" id="name" name="name">
<input type="password" id="name1" name="name1">
</div>
</div>
答案 0 :(得分:1)
这是使它工作的方式。无需将arr
作为参数传递:
function recurse($parent) {
var arr = [];
$parent.children('.dot, input').each(function(){
arr.push($(this).is('input') ? $(this).attr('id') : recurse($(this)));
});
return arr;
}
$(function () {
var elm = $('#container>.dot:first');
console.log(recurse(elm));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div class="dot">
<div class="dot">
<input type="password" id="name2" name="name2">
</div>
<input type="text" id="name" name="name">
<input type="password" id="name1" name="name1">
</div>
</div>
答案 1 :(得分:0)
这是使用香草JS解决问题的方法
const el = document.querySelector('#container > .dot');
function recurse(containerEl) {
const result = [];
const tmp = []; // used to preserve the order [name, name1, [name2]]
const childrenCollection = containerEl.children;
for (let i = 0; i < childrenCollection.length; i++) {
if (childrenCollection[i].tagName === 'DIV') {
tmp.push(recurse(childrenCollection[i]));
} else {
// use this line if you want to fill the array with elements
// result.push(childrenCollection[i]);
// use this line if you just want to retrieve the name attribute
result.push(childrenCollection[i].name);
}
}
return result.concat(tmp);
}
console.log(recurse(el));
<div id="container">
<div class="dot">
<div class="dot">
<input type="password" id="name2" name="name2">
</div>
<input type="text" id="name" name="name">
<input type="password" id="name1" name="name1">
</div>
</div>