2012-04-14 56 views
0

我從XML獲取數據。我可以成功地從XML中獲取價格,但是當我使用下面給出的函數時,會出現一個未定義的意外錯誤:JavaScript中未定義的錯誤

<html> 
    <head> 
    <script type="text/javascript"> 
     function myXml(origin, destination) { 
     var x=xmlDoc.getElementsByTagName("flights"); 

     for(i=0;i<x.length;i++) { 
      if(x[i].getAttribute('FrTLAs')==origin && x[i].getAttribute('destination')==destination) { 
      document.write(x[i].getAttribute('price')) 
      } 
     } 
     } 
    </script> 
    </head> 
    <body> 
    <script type="text/javascript"> 
     document.write(myXml('SYD','Bali')); 
    </script> 
    </body> 
</html> 
+1

xmlDoc未定義。 – 2012-04-14 10:44:12

+0

如果xml沒有定義,那麼我的代碼怎麼會從xml中選擇一個價格。瀏覽器的結果是636undefined – Carlos 2012-04-14 10:44:54

+0

與你的問題無關,但更好的聲明我作爲本地函數作用域中的變量:'for(var i = 0; ..' – Niko 2012-04-14 10:53:18

回答

3

myXml('SYD','Bali')調用返回undefined,因爲你不返回函數體東西。所以

document.write(myXml('SYD','Bali')); 

將打印"undefined"。只是這個替換上面的代碼:

myXml('SYD','Bali'); 
1

工程師是正確的,或更好的回報從myXml功能的價值。

因此,document.write(undefined)不會發生,您可能不會收到上述錯誤。