2013-02-22 82 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之后加载。

相关问题