2012-03-24 61 views
22

我正在嘗試做一些相當簡單的事情,但由於我可能沒有足夠好的搜索文檔的原因,所以無法使其工作。Javascript:Uncaught TypeError:無法調用方法'addEventListener'null

我有一個正常的內聯JS,看起來像這樣:

<A title="Wolfram IP Calc" href="javascript:txt=prompt('Enter%20IP%20address,%20e.g.%2010.20.30.40/29','1.2.3.4/5');%20if(txt)%20window.open('http://www.wolframalpha.com/input/?i='+txt);void(O);">Compute!</A> 

由於種種原因,我想單獨的JS,而這正是我碰釘子。

我創建了下面的測試頁面,給我的錯誤Uncaught TypeError: Cannot call method 'addEventListener' of null

<HTML> <HEAD profile="http://www.w3.org/2005/10/profile"> <script type="text/javascript"> 
var compute = document.getElementById('compute'); 
compute.addEventListener('click', computeThatThing, false); 

function computeThatThing() { 
    txt=prompt('Enter%20IP%20address,%20e.g.%2010.20.30.40/29','1.2.3.4/5'); 
    if(txt) { 
     window.open('http://www.wolframalpha.com/input/?i='+txt); 
    } 
} 
</script></HEAD> 
<BODY> 
<A title="Wolfram IP Calc" id="compute" href="javascript:void(O);">Test</A> 
</BODY> 
</HTML> 

我已經能夠找到點,這樣的一個問題是,addEventListener不能工作的唯一的事與<A>但應該處理<IMG>(這很適合我,因爲我要倒這對一些圖像),所以我嘗試添加以下無濟於事:

<img id="compute" src="http://products.wolframalpha.com/images/products/products-wa.png" /> 

在此先感謝您指出我」做錯了。這可能很明顯,但我對JS的接近零經驗,到現在我需要它的時候,我主要是通過貨運提供服務。

+0

使用jQuery。 $(document).ready(function(){<這裏所有的東西都在dom準備好的時候被加載了。 – PhillipKregg 2012-03-24 22:31:26

+1

@PhillipKregg,我覺得將Jquery添加到我的項目中會增加不必要的複雜性和加載時間。 – Jan 2012-03-25 00:46:13

+0

@PhillipKregg這是專門針對一個項目,其中一切都包含在一個文件中,包括base64編碼圖像,因此它沒有外部依賴關係。 – Jan 2012-03-25 05:21:38

回答

54

你的代碼是在<head> =>運行之前的元素呈現,所以document.getElementById('compute');返回NULL,因爲MDN承諾...

element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.

MDN

解決方案:

  1. 將腳本放在頁面的底部。
  2. 在加載事件中調用附加代碼。
  3. 使用jQuery庫和它的DOM就緒事件。

什麼是jQuery ready事件?

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...

readydocs

+1

謝謝'gdoron'!解決方案1立即開始工作。我真的很驚訝,這是簡單而直接的。現在打破我的生產代碼! :) – Jan 2012-03-24 22:30:02

+0

我在面對morris圖表時面臨同樣的問題。我已經完成了這一切,但仍然沒有希望。 – Abhinav 2016-10-26 13:14:30

相關問題