2013-06-13 11 views
19

Ho questo codice in una funzione:Come faccio a scorrere gli oggetti figli in javascript?

tableFields = tableFields.children; 
for (item in tableFields) { 
    // Do stuff 
} 

Secondo un console.log di TableFields, sto ottenendo un allineamento indietro come presumo che devo fare. Un console.log dell'elemento all'interno dei loop restituisce undefined. Cosa devo fare per passare in rassegna i TableFields e inserire ogni oggetto in una tabella?

log della console di TableFields:

HTMLCollection[label, input, label, input 25, label, input, input, input Remove] 


0 
label 

1 
input 

2 
label 

3 
input 25 

4 
label 

5 
input 

6 
input 

7 
input Remove 

description[] 
input 

hours[] 
input 

invoice_number 
input 

getlength 
8 

rate[] 
input 25 

item 
item() 

iterator 
iterator() 

namedItem 
namedItem() 

__proto__ 
HTMLCollectionPrototype { item=item(), namedItem=namedItem(), iterator=iterator()} 

Qui è l'intera sezione di codice come ho finora:

$this->title("Test"); 
    $this->defaultMenu(); 
    $select = ""; 
    $names = Customer::getNames(); 
    foreach ($names as $id => $name) { 
     $select .= '<option value="'.$id.'"'; 
     if ($this->customerid == $id) $select .= ' selected '; 
     $select .= '>'.$name.'</option>'; 
    } 

    $form = ' 
<script type="text/javascript"> 

var counter = 0; 

function isEven(int){ 
int = Number(int); 
return (int%2 == 0); 
} 



function moreLabor() { 

    var table = document.getElementById("editTable"); 
    var tableFields = document.getElementById("readroot"); 

    tableFields = tableFields.children; 
    console.log(tableFields); 
    for (item in tableFields) { 

     if (isEven(counter)) { 
      var tableRow = table.insertRow(-1); 
      var label = tableRow.insertCell(-1); 
      console.log(tableFields[item]); 
      label.appendChild(tableFields[item]); 

     } else { 
      var field = tableRow.insertCell(-1); 
      field.innerHTML = item.innerHTML; 


     } 

     counter++; 
    } 

    console.log(); 
var insertHere = document.getElementById("writeroot"); 
} 

window.onload = function(){ 
    document.getElementById(\'moreLabor\').onclick = function(){ moreLabor(); } 
    moreLabor(); 
} 


</script> 

<div id="readroot" style="display: none"> 
<tr> 
    <td><label for="hours">Hours:</label></td> 
    <td><input type="text" name="hours[]" value="" /></td> 
</tr> 
<tr> 
    <td><label for="rate">Rate:</label></td> 
    <td><input type="text" name="rate[]" value="25" /></td> 
</tr> 
<tr> 
    <td><label for="description">Description:</label></td> 
    <td><input type="text" name="description[]" value="" /></td> 
</tr> 

<input type="hidden" name="invoice_number" value="'.$this->number.'" /> 
<tr> 
    <td><input type="button" value="Remove" 
    onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /></td> 
</tr> 

</div> 

<form method="POST" class="invoice" id="edit"> 
<table id="editTable"> 
    <tr> 
     <td><label>Work Order Number:</label></td> 
     <td><input type="text" name="number" value="'.$this->number.'"/></td> 
    </tr> 
    <tr> 
     <td><label>Customer:</label></td> 
     <td><select name="customerid">'.$select.'</select></td> 
    </tr> 
    <span id="writeroot"></span> 

    <tr> 
     <td><input type="button" id="moreLabor" value="Add labor"/></td> 
     <td><input type="submit" name="Save" value="Save" /></td> 
    </tr>'; 
    if (!is_null($this->id)) { 
     $form .= '<input type="hidden" name="id" value="'.$this->id.'"/>'; 
    } 
    $form .= '</table></form>'; 



    $this->component($form); 

risposta

40

Il trucco è che the DOM Element.children attribute non è un array, ma un nell'edificio- come collezione che ha lunghezza e può essere indicizzato come un array, ma non è un array:

var children = tableFields.children; 
for (var i = 0; i < children.length; i++) { 
    var tableChild = children[i]; 
    // Do stuff 
} 

Incidentalmente, in generale, è una procedura migliore per eseguire un'iterazione su un array utilizzando un ciclo di base anziché un ciclo for-in-loop.

+0

così come ottengo gli elementi interni di un elemento genitore? –

+0

@CoreyRay: nel mio codice di esempio "campiCampi" è l'elemento genitore e "figli" sono gli elementi figlio. – maerics

+1

Ho trovato che funziona correttamente: 'for (lascia x di Array.from (tableFields.children)) {...}' – Alleo

4

se tableFields è un array, è possibile scorrere elementi come segue:

for (item in tableFields); { 
    console.log(tableFields[item]); 
} 

proposito ho visto un errore logico in you'r code.just rimuovere ; dalla fine del ciclo

proprio qui:

for (item in tableFields); {.

ciò causerà you'r ciclo per fare proprio nothing.and la seguente linea sarà eseguito solo una volta:

// Do stuff 
+0

Grazie, ho apportato le modifiche suggerite. Sto cercando di aggiungere questi oggetti a un oggetto riga tabella –

0

La versione compatibile (IE9 +) è

var parent = document.querySelector(selector); 
Array.prototype.forEach.call(parent.children, function(child, index){ 
    // Do stuff 
}); 

L'ES6 il modo è

const parent = document.querySelector(selector); 
Array.from(parent.children).forEach((child, index) => { 
    // Do stuff 
}); 
Problemi correlati