简体   繁体   中英

Javascript for-loop not looping

A common question but seriously why is my loop not working? What error have i made, any help would be appreciated :)

XML

<?xml version="1.0" encoding="utf-8"?>
<School>
  <child>
    <name>john</name>
    <dob>28-09-2000</dob>
    <age>15</age>
    <add>jgdkhcjgvbv</add>
    <phone>12345678</phone>
  </child>
  <child>
    <name>henry</name>
    <dob>19-09-2001</dob>
    <age>14</age>
    <add>kjdfndsjnlae</add>
    <phone>23456789</phone>
  </child>
  <child>
    <name>luke</name>
    <dob>27-04-1999</dob>
    <age>16</age>
    <add>ksmfodnzsksl</add>
    <phone>34567890</phone>
  </child>
</School>

HTML

<html>
<head>
<script type="text/javascript" >
    var xmlObject, docObject, childarray, cname, cdob, cage;
    xmlObject = new XMLHttpRequest();
    xmlObject.open("GET","school.xml",false);
    xmlObject.send();
    docObject = xmlObject.responseXML;
    childarray=docObject.getElementsByTagName("child");

    for (var i = 0; i<childarray.length; i++) {
        cname = docObject.getElementsByTagName("name")[i].childNodes[0].nodeValue;
        document.write("Name : " + cname + "<BR/>");

        cdob = docObject.getElementsByTagName("dob")[i].childNodes[0].nodeValue;
        document.write("Dob : " + cdob + "<BR/>");

        cage = docObject.getElementsByTagName("age")[i].childNodes[0].nodeValue;
        document.write("Age : " + cage + "<BR/>");

        cadd = docObject.getElementsByTagName("add")[i].childNodes[0].nodeValue;
        document.write("Add : " + cadd + "<BR/>");

        cphone = docpb.getElementsByTagName("phone")[i].childNodes[0].nodeValue;
        document.write("Phone : " + cphone + "<BR/>");

    }
</script>
<title>school</title>
</head>
<body>
</body>
</html>

What i want to do is to print the name, dob, age, address, phone for 'n' number of students at a time. The code only shows the first child's details.

Welp

Have you tried adding "=" in

var i = 0; i<=childarray.length; i++

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM