使用javascript

时间:2015-11-22 22:07:36

标签: javascript xml

我正在尝试从xml文件中获取颜色十六进制代码,并使用这些数据来更改20个div的颜色。我已经迷失了,并试图挑选我发现并用于自己的代码片段。我收到控制台错误无法读取属性“innerhtml”。

我在这里做错了什么?

HTML

<div class='container'>
        <div class='blah' id='1'>hello</div>
        <div class='blah' id='2'>hello</div>
        ........
        <div class='blah' id='19'>hello</div>
        <div class='blah' id='20'>hello</div>
    </div>
    <input type="button" value="changediv" onclick="setTheColors()">

XML

<?xml version="1.0" encoding="UTF-8"?>
<divcolors>
    <div name ="1"><color>#94fd05</color></div>
    <div name ="2"><color>#c8a522</color></div>
    ..........
    <div name ="19"><color>#66b013</color></div>
    <div name ="20"><color >#223fc5</color></div>
</divcolors>

的javascript

function changeColors(xml) {
    var xmlDoc = xml.responseXML;
    var colorColor = xmlDoc.getElementsByTagName("div");
    for (var i = 0; i < colorColor.length; i++){
        var current = colorColor[i].getAttribute('name');
        var theDiv = document.getElementById(current);
        theDiv.style.backgroundColor = colorColor[i].childNodes[0].nextSibling.innerHTML;
    }
}

function setTheColors(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            changeColors(xhttp);
        }
    };
    xhttp.open("GET", "divcolors.xml", true);
    xhttp.send();
}

这行代码给出了控制台错误:

theDiv.style.backgroundColor = colorColor[i].childNodes[0].nextSibling.innerHTML;

完全失去了如何让它发挥作用。我尝试了很多东西,没有任何效果。我能让代码做的唯一另一件事就是不给我任何控制台错误,但同时什么都不做。

1 个答案:

答案 0 :(得分:0)

忽略“nextSibling”!

var xml = '<divcolors><div name ="1"><color>#94fd05</color></div><div name ="2"><color>#c8a522</color></div><div name ="19"><color>#66b013</color></div><div name ="20"><color >#223fc5</color></div></divcolors>';

var changeColors = function() {
    var parser = new DOMParser();
    var xmlDoc = parser.parseFromString(xml, "text/xml");
    var colorColor = xmlDoc.getElementsByTagName("div");
    for (var i = 0; i < colorColor.length; i++) {
        var current = colorColor[i].getAttribute('name');
        var theDiv = document.getElementById(current);
        theDiv.style.backgroundColor = colorColor[i].childNodes[0].innerHTML;
    }
}
<div class='container'>
    <div class='blah' id='1'>hello</div>
    <div class='blah' id='2'>hello</div>........
    <div class='blah' id='19'>hello</div>
    <div class='blah' id='20'>hello</div>
</div>
<input type="button" value="changediv" onclick="changeColors()">