未捕获的类型错误:无法读取属性'style'为null

Uncaught TypeError: Cannot read property 'style' of null

本文关键字:属性 style null 读取 类型 错误      更新时间:2023-09-26

我有一个从XML文件中读取协调的函数,当它在窗口中松散时,该函数可以很好地工作。但当我把它放在函数中时,就会出现错误。第127行的CCD_ 1。

第127行是

document.getElementById(id).style.top=Ynod;

有什么想法吗?

var main = (function () {
    var id=Math.floor((Math.random()*1000000)+1);

    document.getElementById("add-new-sticker-btn").addEventListener("click", function(){
        id += 1;
        console.log(id);
        add_sticker(""); /**"" removes undefined "*/
        var xmlhttp;
        xmlhttp=new XMLHttpRequest();
        xmlhttp.open("POST","/project2/php/insert.php",true); /*Search way... JS to javaScript*/
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send("textBoxID="+id);
    });

    function run() {
        readXml();
    }
    function readXml() {
        var xmlhttp;
        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("get", 'xml/stickers.xml', false);
        xmlhttp.send();
        var myXML = xmlhttp.responseXML;
        stickers = myXML.getElementsByTagName("sticker");
        for (i = 0; i < stickers.length; i++) {
            var idNod = (stickers[i].getElementsByTagName("id")[0].childNodes[0].nodeValue); /*Get the ID*/
            var id = idNod;
            var textNod = (stickers[i].getElementsByTagName("text")[0].childNodes[0].nodeValue); /* Text*/
            add_sticker(textNod); /*Call creator function*/
            var Xnod = (stickers[i].getElementsByTagName("x")[0].childNodes[0].nodeValue) + 'px'; /*Get the x position Add PX for pixel*/
            var Ynod = (stickers[i].getElementsByTagName("y")[0].childNodes[0].nodeValue) + 'px'; /*Get the y position*/
            var Znod = (stickers[i].getElementsByTagName("z")[0].childNodes[0].nodeValue); /*Get the y position*/
            console.log(Ynod) // Gives correct Y and X
            console.log(Xnod)
            document.getElementById(id).style.top = Ynod;
            document.getElementById(id).style.left = Xnod;
            document.getElementById(id).style.zIndex = Znod;
        }
    }
    window.addEventListener("load", run);
    return {};
}());

idNod未定义,请确保贴纸中有元素,并尝试将贴纸[i].getElementsByTagName("id"([0].childNodes打印到控制台。

Okej我自己发现了这个问题。我调用了一个全局变量var id = idNod;如果我将var id = idNod;更改为仅id=idNod一切正常:(