我的 javascript 程序基本上创建一系列图像并随机选择一个图像并将其 src 设置为特定路径。然而,由于某种原因,代码有时似乎会卡住。在我的程序中,我调用其中一个图像的 element.parentNode 以便用 anchor 标记包围它,但它会抛出一个控制台错误,指出它无法获取未定义或空引用的属性“parentNode”,尽管事实上有时,代码有时实际上会执行,而无需对代码进行任何更改。我必须多次刷新才能幸运地不引发错误并且其余代码顺利执行。 这是我的代码:
var id = generateRandom(325);
var el = document.getElementById(id.toString());
var anchor = document.createElement("a");
var nextPage = "level" + (level + 1).toString() + ".html";
if (level == 3) {
nextPage = "win.html";
}
anchor.setAttribute("href", nextPage);
el.parentNode.insertBefore(anchor, el); // line 54
错误:
SCRIPT5007: Unable to get property 'parentNode' of undefined or null reference
scripts.js (54,2)
编辑: 更新了整个功能
var div = document.getElementById("images");
var time = parseInt(document.getElementsByClassName("timer")[0].innerHTML);
var level = getLevel(time);
var rows = 13;
var cols = 23;
for (var i = 1; i <= rows; i++) {
var marquee = document.createElement("marquee");
marquee.setAttribute("scrollamount", 30);
for (var j = 1; j <= cols; j++) {
var img = document.createElement("img");
img.setAttribute("src", getPath());
img.setAttribute("id", (i * j).toString());
img.setAttribute("width", "80px");
img.setAttribute("height", "70px");
marquee.appendChild(img);
}
div.appendChild(marquee);
}
var id = generateRandom(rows * cols);
var el = document.getElementById(id.toString());
var anchor = document.createElement("a");
var nextPage = "level" + (level + 1).toString() + ".html";
if (level == 3) {
nextPage = "win.html";
}
anchor.setAttribute("href", nextPage);
el.parentNode.insertBefore(anchor, el);
var input = document.createElement("input");
input.setAttribute("type", "image");
input.setAttribute("width", "80px");
input.setAttribute("height", "70px");
input.setAttribute("src", "resources\\asotigue.jpg");
el.parentNode.replaceChild(input, el);
anchor.appendChild(input);
生成随机函数:
function generateRandom(n) {
return Math.floor((Math.random() * n) + 1);
}
最佳答案
此方法将收集当前页面上可用的某个类别的项目的所有 id,并随机返回其中一个 id。
您可以在 fiddle 中看到它的工作原理。 。检查控制台。
function getIdsListByClassName(className) {
var elements = document.querySelectorAll('[id].' + className); // get all items that have the id attribute and the defined class name
var ids = Array.prototype.slice.call(elements, 0).map(function (element) {
return element.getAttribute('id');
}); // convert the elements list to array, and map it to ids
var currentIndex = Math.floor(Math.random() * ids.length); // get an index between 0 and ids.length - 1
return ids[currentIndex];
}
关于javascript - 无法获取未定义或空引用的属性 'parentNode',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32033472/