2013-02-22 84 views
0

我目前正在一個網站上工作。我想要它做的是當你加載頁面倒計時開始,15秒後出現一個按鈕。jQuery Uncaught TypeError?

目前,它完美的作品我的測試服務器上,並在的jsfiddle。但是,當我將它移動到我的Web服務器時,它不起作用。我在Google Chrome的控制檯中看了一下,發現以下錯誤。

downloadButton.parentNode.replaceChild(newElement, downloadButton); 
Uncaught TypeError: Cannot read property 'parentNode' of null 

下面是完整的代碼(見的jsfiddle http://jsfiddle.net/6zchq/

var downloadButton = document.getElementById('download'); 
var counter = 15; 
var newElement = document.createElement('p'); 
newElement.innerHTML = 'Getting your file, please wait 15 seconds.'; 
var id; 

downloadButton.parentNode.replaceChild(newElement, downloadButton); 

id = setInterval(function() { 
    counter--; 
    if(counter < 0) { 
     newElement.parentNode.replaceChild(downloadButton, newElement); 
     clearInterval(id); 
    } else { 
     newElement.innerHTML = "Getting your file, please wait " + counter.toString() + " seconds."; 
    } 
}, 1000); 

我敢肯定,這是一個簡單的問題,我只是不明白,爲什麼它不工作。

任何幫助表示讚賞!

謝謝。

+3

問題jQuery在哪裏? – j08691 2013-02-22 18:20:57

+0

好吧,如果代碼在你的服務器和小提琴上工作正常,那麼代碼必須是正確的。你期望我們做什麼?我們如何解決我們沒有得到的錯誤?但是,錯誤消息似乎表明'document.getElementById('download')'返回null,在這種情況下,請看這個問題:[「爲什麼jQuery或者像getElementById這樣的DOM方法不行找到元素?「(http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element)。 – 2013-02-22 18:22:40

+0

如果'downloadButton'爲null,那麼您的JS可能正在腳本的頂部執行。將其放入bodys onload函數或頁面底部。 – sachleen 2013-02-22 18:23:56

回答

3

嘗試在準備功能包裹你的代碼。

的原因將是一個真正的web服務器加載延遲意味着您嘗試訪問現在還沒有的元素。

+0

謝謝,這是問題。 – Authentic 2013-02-22 18:58:11

1

據推測,當DOM還沒有完全加載和下載按鈕元素尚不存在的代碼運行。在ready/onload處理程序中運行代碼,或者將Javascript放在頁面的body標籤的底部,以便在頁面的HTML之後加載。

相關問題