2013-08-01 16 views
5

Właśnie zacząłem czytać JavaScript i próbuję napisać małą funkcję rekursywną, która przeszuka dane węzły i zwróci listę wartości jako ciąg znaków.Javascript - Funkcja rekursywna do iteracji poprzez elementy

Moja struktura HTML może być coś podobnego

<div id="parentfolder">parentfolder1 
    <div class ="item1">item1</div> 
    <div class ="item2">item2</div> 
    <div id="parentfolder">parentfolder2 
     <div class ="item1">item1</div> 
     <div class ="item2">item2</div> 
    </div> 
</div> 

i tu jest mój funkcji JavaScript:

function jsoncreator(parentfolderclass){ 
    var jstring = ''; 

    //get first occurance of parent folder 
    var parentfolder = document.getElementById(parentfolderclass); 
    var childnodes = parentfolder.childNodes; 

    for (property in childnodes){ 
     jstring += property+ childnodes[property]; 
     if(childnodes[property] === parentfolderclass){ 
      jsoncreator(parentfolderclass); 
      jstring += childnodes[property].value + '<br>'; 
     } 
     else{ 
      //jstring += childnodes[i].value + '<br>'; 
     } 
    } 
    document.write(jstring); 
} 

Wszystko im powrót znaczy

0[object Text]1[object HTMLDivElement]2[object Text]3[object HTMLDivElement]4[object Text]5[object HTMLDivElement]6[object Text]length7itemfunction item() { [native code] } 

Kiedy próbuję wydrukować wartości childnodes, dostaję garść niezdefiniowanych zwrotów.

Jeśli ktoś mógłby wyjaśnić, co robię źle, byłbym bardzo wdzięczny.

+0

Po raz pierwszy zduplikowane identyfikatory są nieprawidłowym kodem HTML. Poza tym nie opisałeś dokładnie, co powinna zawierać dokładnie zwrócona tablica. –

+0

@ FabrícioMatté zwróci listę wartości w postaci ciągu znaków – dudemanbearpig

+0

"Wartości" jak w ich treści tekstowej? –

Odpowiedz

8

Trzeba będzie coś zrobić jak poniżej (rekurencyjnej cross-browser)

Javascript

function walkTheDOM(node, func) { 
    func(node); 
    node = node.firstChild; 
    while (node) { 
     walkTheDOM(node, func); 
     node = node.nextSibling; 
    } 
} 

function textNodeValuesToArray(node) { 
    if (typeof node === "string") { 
     node = document.getElementById(node); 
    } 

    var arrayOfText = []; 

    function pushText(currentNode) { 
     if (currentNode.nodeType === 3) { 
      arrayOfText.push(currentNode.nodeValue); 
     } 
    } 

    walkTheDOM(node, pushText); 

    return arrayOfText; 
} 

console.log(textNodeValuesToArray("parentfolder")); 

Na jsfiddle

lub używając treewalker

Browser compatibility

Supported by IE9+, FF2+, Chrome 1+, Safari 3+, Opera 9+

JavaScript

function textNodeValuesToArray(node) { 
    if (typeof node === "string") { 
     node = document.getElementById(node); 
    } 

    var arrayOfText = [], 
     treeWalker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, { 
      acceptNode: function (node) { 
       return NodeFilter.FILTER_ACCEPT; 
      } 
     }, false); 

    while (treeWalker.nextNode()) { 
     arrayOfText.push(treeWalker.currentNode.nodeValue); 
    } 

    return arrayOfText; 
} 

console.log(textNodeValuesToArray("parentfolder")); 

Na jsfiddle

Bez rekursji i cross przeglądarce byłoby coś takiego

Javascript

Avoid using labels

Labels are not very commonly used in JavaScript since they make programs harder to read and understand. As much as possible, avoid using labels and, depending on the cases, prefer calling functions or throwing an error.

function walkDOM(root, func) { 
    var node = root; 

    start: while (node) { 
     func(node); 
     if (node.firstChild) { 
      node = node.firstChild; 
      continue start; 
     } 

     while (node) { 
      if (node === root) { 
       break start; 
      } 

      if (node.nextSibling) { 
       node = node.nextSibling; 
       continue start; 
      } 

      node = node.parentNode; 
     } 
    } 
} 

function textNodeValuesToArray(node) { 
    if (typeof node === "string") { 
     node = document.getElementById(node); 
    } 

    var arrayOfText = []; 

    function pushText(currentNode) { 
     if (currentNode.nodeType === 3) { 
      arrayOfText.push(currentNode.nodeValue); 
     } 
    } 

    walkDOM(node, pushText); 

    return arrayOfText; 
} 

console.log(textNodeValuesToArray("parentfolder")); 

Na jsfiddle

+1

Twoja odpowiedź rozwiała mój umysł. – dudemanbearpig

1
<div id="parentfolder">parentfolder1 
    <div class ="item1">item1</div> 
    <div class ="item2">item2</div> 
    <div class="subfolder">parentfolder2 
    <div class ="item1">item1</div> 
    <div class ="item2">item2</div> 
    </div> 
</div> 



var children = document.getElementById('parentfolder').getElementsByClassName('*'); 
var childValues = new Array(); 

for(i=0; i<children.length; i++) { 
    if(children[i].className == 'subfolder') { 
    continue; 
    } else { 
    childValues.push(children[i].innerHTML); 
    } 
} 
+0

Prawdopodobnie oznaczałeś Tag zamiast klasy w 'getElementsByTagName ('*')', a 'childValues ​​[] = ...' nie jest prawidłową składnią JS. –

+0

childValues ​​[] = ... nie jest prawidłową składnią JS. Tak - utknął w trybie PHP. Naprawiony. I nie - miałem na myśli getElementsByClassName ("*") –

+1

Jesteś pewien? http://jsfiddle.net/PnEvM/ ':)' –

Powiązane problemy