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

Cor*_*Ray 35 javascript

我在函数中有这个代码:

tableFields = tableFields.children;
for (item in tableFields) {
    // Do stuff
}
Run Code Online (Sandbox Code Playgroud)

根据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()}
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止的整个代码部分:

$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);
Run Code Online (Sandbox Code Playgroud)

mae*_*ics 66

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

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

顺便提一下,通常使用基本for循环而不是for-for循环迭代数组是更好的做法.

  • 我发现这个工作正常:`for(让x of Array.from(tableFields.children)){...}` (4认同)

小智 12

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

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


Beh*_*ili 6

如果tableFields是数组,则可以如下遍历元素:

for (item in tableFields); {
     console.log(tableFields[item]);
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我在您的代码中看到了逻辑错误。只需;从for循环的末尾删除

就在这儿 :

for (item in tableFields); {

这将导致您的循环不执行任何操作。并且以下行将仅执行一次:

// Do stuff
Run Code Online (Sandbox Code Playgroud)


cod*_*key 5

向后兼容版本 (IE9+) 是

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

es6的方式是

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


Dat*_*yen 5

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

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