窗口加载后找不到元素的代码

时间:2014-04-22 03:49:59

标签: javascript html window

我用JS编写了一小段代码来改变页面的主题。有一个调用此代码的按钮,JS代码应该在选中时围绕按钮创建边框。但是,即使我在页面重新加载后调用此代码,Google Chrome的开发人员工具仍然会说," Uncaught TypeError:无法读取属性' style' of null"。它指的是添加边框的代码行。

以下是HTML页面上的按钮:

<div id="colBlack" title="Theme: Black" onclick="changeBackColor('Black')"></div>
<div id="colWhite" title="Theme: White" onclick="changeBackColor('White')"></div>

以下是一些JS代码(PHP响应将返回&#34; Black&#34;或&#34; White&#34;处理完一些信息后):

window.onload = function() {
    // irrelevant lines of code
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET","res/setTheme.php",true);
    xmlhttp.send();
    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
            changeBackColor(xmlhttp.responseText);
    // irrelevant lines of code
}
function changeBackColor(color) {
    if(color == "White") {
        opp = "Black";
        right = "48px";
    } else {
        opp = "White";
        right = "78px";
    }
    document.getElementById("col" + color).style.border = "2px solid " + opp;  // line of code Google Developing Tools refers to
    document.getElementById("col" + opp).style.border = "none";
    document.getElementById("col" + opp).style.top = "10px";
    document.getElementById("col" + color).style.top = "8px";
    document.getElementById("col" + color).style.right = right;
    document.getElementsByClassName("body")[0].style.backgroundColor = color;
    var elemType = Array("p","span","h1","h2","h3","h4","h5","h6");
    for(var tE = 0; tE < 8; tE++) {
        for(var textElem = 0; textElem <     document.getElementsByTagName(elemType[tE]).length; textElem++) {
            if(window.getComputedStyle(document.getElementsByTagName(elemType[tE])[textElem],null).getPropertyValue("color") == "rgb(0, 0, 0)" || window.getComputedStyle(document.getElementsByTagName(elemType[tE])[textElem],null).getPropertyValue("color") == "rgb(255, 255, 255)")
                document.getElementsByTagName(elemType[tE])[textElem].style.color = opp;
        }
    }
}

是因为changeBackTheme函数在window.onload之外,并且在被调用之前被解析了吗?如果是这样,我该如何阻止它?如果没有,问题是什么?

如果您需要更多代码来解决这个问题,请告诉我。

感谢。

0 个答案:

没有答案