2015-08-16 224 views
1

我的JavaScript程序基本上創建一系列圖像,並隨機選取一個並將其src設置爲特定路徑。但是,由於某些原因,代碼似乎有時會卡住。在我的程序中,我調用其中一個圖像的element.parentNode,以便用一個錨標記來包圍它,但它會拋出一個控制檯錯誤,指出它無法獲取未定義或空引用的屬性'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); 
} 
+2

顯然你的'generateRandom()'函數有時會返回一個在你的DOM中不存在的ID。 – slash197

回答

0

現在編輯您已包含更多代碼:您正在生成13 * 23 = 299元素,但選擇了一個隨機元素高達325,因此有時您沒有足夠的元素用於隨機選擇。


那麼,究竟該代碼告訴你的是,el變量是undefinednull。有幾個原因可能是:

  1. generateRandom(325)正在生成一個ID值是不存在的頁面。

  2. 在頁面完成加載和解析之前您正在調用document.getElementById(id.toString());,因此有些頁面元素尚未出現。只有在頁面加載到<body>的末尾或等待DOMContentLoaded事件觸發後才能運行腳本。

僅供參考,如果你的問題是第二個,你可以讀到這裏pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it使用普通的JavaScript的各種解決方案。


如果你知道有時候generateRandom(325)會挑一個元素的ID是不是在頁面上,你想允許,但抵禦它停止執行你的代碼,那麼你可以檢查該條件:

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); 
if (el) { 
    el.parentNode.insertBefore(anchor, el); 
} 

爲了幫助你跟蹤你偶爾的錯誤,在此之後右:

var id = generateRandom(rows * cols); 
var el = document.getElementById(id.toString()); 

您可以添加這個額外的調試代碼:

// add this to detect what situation you get a missing element 
if (!el) { 
    console.log("did not find id when: rows = " + rows + ", cols = " + cols"); 
} 
+0

我正在尋找的所有元素實際上都是由JavaScript代碼本身生成的,所以這些元素應該在特定代碼運行時出現 – JavaFanatic

+0

@JavaFanatic - 我毫不懷疑它們「應該」可以從其他代碼中使用,但顯然有些東西不對,或者'el'不會是'null'。也許你的其他代碼有一個錯誤,它不會產生你認爲它的所有東西,或者不會將它們全部插入到DOM中,所以它們可以通過'document.getElementById()'找到。 – jfriend00

+0

謝謝。 :)我意識到我的代碼有一個錯誤,它涉及到錯誤計算。我改變了它,以便隨機數的上限實際上由行*列設置,而不是固定的數字 – JavaFanatic

0

這種方法將收集與頁面上可用的某一類項目的所有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]; 
} 
相關問題