如何遍历DOM以准备树结构数组

时间:2019-01-05 17:01:01

标签: javascript jquery arrays object

我想通过使用Javascript / jQuery遍历DOM来准备嵌套数组。感兴趣的元素位于#container元素中,或者具有dot类,或者是input元素。

我想准备像[name,name1,[name2]]这样的数组。我在这里使用了最常用的技术,例如递归。但是我无法使它起作用:

fiddle

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

2 个答案:

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