如何在javascript中循环访问子对象?

时间:2013-06-13 18:18:39

标签: javascript

我在函数中有这段代码:

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

根据tableFields的console.log,我得到一个数组,因为我认为我需要这样做。循环中的console.log项返回undefined。我需要做什么来遍历tableFields并将每个对象插入表中?

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()}

以下是我到目前为止的整段代码:

$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);

7 个答案:

答案 0 :(得分:58)

诀窍是the DOM Element.children attribute不是数组而是类似数组的集合,它有长度并且可以像数组一样索引,但它不是数组:

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

顺便说一句,一般来说,使用基本for循环而不是for-in-循环迭代数组是一种更好的做法。

答案 1 :(得分:6)

如果tableFields是一个数组,您可以按如下方式遍历元素:

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

顺便说一下,我在你的代码中看到了一个逻辑错误。从for循环结束中删除;

就在这里:

for (item in tableFields); {

这将导致你的循环不执行任何操作。以下行只会执行一次:

// Do stuff

答案 2 :(得分:3)

ECS6 中,人们可以使用Array.from()

const listItems = document.querySelector('ul').children;
const listArray = Array.from(listItems);
listArray.forEach((item) => {console.log(item)});

答案 3 :(得分:2)

向后兼容版本(IE9 +)是

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

es6方式是

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

答案 4 :(得分:2)

在 2020 / 2021 年,使用 Array.from 可以更轻松地从类似数组的节点“转换”为实际数组,然后使用 .map 循环遍历生成的数组。 代码很简单,如下:

Array.from(tableFields.children).map((child)=>console.log(child))

答案 5 :(得分:2)

现代 JS 还使用 for..of 使我们能够迭代 DOM 子对象、数组或其他可迭代对象。我认为它非常干净和简单。

var children = tableFields.children;
for (c of children) { 
  console.log(c);
  // Do stuff with child c
}

答案 6 :(得分:0)

我很惊讶没有人回答以下代码:

for(var child=elt.firstChild;
    child;
    child=child.nextSibling){
  do_thing(child);
}

或者,如果您只想要子元素, 此代码:

for(var child=elt.firstElementChild;
    child;
    child=child.nextElementSibling){
  do_thing(child);
}
相关问题