簡體   English   中英

未捕獲的TypeError:無法讀取null的屬性“樣式”

[英]Uncaught TypeError: Cannot read property 'style' of null

我有一個從XML文件讀取協調的函數,該函數在窗口中松散時可以正常工作。 但是當我將其放在函數中時,我得到了錯誤。 Cannot read property 'style' of null. 在第127行。

第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一切正常:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM