javascript 未捕获的类型错误:无法读取 null 的属性“样式”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15613058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Cannot read property 'style' of null
提问by Dymond
I have this function that reads coordination from a XML file, the function works fine when its loose in the window. but when I put it inside a function, then I get the error. Cannot read property 'style' of null.
on row 127.
我有这个从 XML 文件读取协调的函数,当它在窗口中松动时,该函数工作正常。但是当我把它放在一个函数中时,我得到了错误。Cannot read property 'style' of null.
在第 127 行。
The row 127 is
第 127 行是
document.getElementById(id).style.top=Ynod;
Any ideas ?
有任何想法吗 ?
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 {};
}());
回答by JimCresswell
idNod is undefined, make sure there are elements in stickers and try printing stickers[i].getElementsByTagName("id")[0].childNodes to the console.
idNod 未定义,请确保贴纸中有元素并尝试将贴纸 [i].getElementsByTagName("id")[0].childNodes 打印到控制台。
回答by Dymond
Okej I found the problem my self.
I was calling a global variable var id = idNod;
If I changed the var id = idNod;
to only id=idNod
everything worked :)
好的,我自己发现了这个问题。我正在调用一个全局变量 varid = idNod;
如果我将其更改var id = idNod;
为仅id=idNod
一切正常:)