我的JavaScript程序基本上会创建一系列图像并随机选择一个并将其src设置为特定路径。但是,由于某种原因,该代码有时会卡住。在我的程序中,我正在调用其中一幅图像的element.parentNode以便用锚标记将其包围,但是它抛出一个控制台错误,表示尽管存在以下事实,但它无法获得未定义或空引用的属性“ 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);


generateRandom函数:

 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];
}

10-05 20:34
查看更多