2013-04-27 71 views
0

我正在學習一點HMTL5來準備參加70-480考試。我正在嘗試做一些JavaScript代碼。它看起來是這樣的:javascript運行時錯誤0x800a1391

function inchestometers(inches) { 
    if (inches < 0) 
     return -1; 
    else { 
     var meters = inches/39.37; 
     return meters; 
    } 
} 

var inches = 12; 
var meters = inchestometers(inches); 
document.write("the value in meters is " + meters); 


var hello = document.getElementById("hello"); 
hello.firstChild.nodeValue = "Hello World"; 

,我有這樣的html代碼:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title>Htnl 5 test</title> 
    <script src="script/test.js"></script> 

</head> 

<body> 

<p id="hello">Hello</p> 

</body> 
</html> 

在我的VS 2012我已經使用了Asp.net空的Web應用程序項目並添加JS文件,也是html文件。問題是該函數正常運行,沒有任何豁免。這個功能是從這裏取得的:http://msdn.microsoft.com/en-us/library/cte3c772(v=vs.94).aspx

但是,當我試圖運行代碼的地方,我得到的文檔元素'crashint與主題中的錯誤。我調查的是,你好得到空值。我也嘗試了從這裏thak代碼:

http://msdn.microsoft.com/en-us/library/yfc4b32c(v=vs.94).aspx - 與div的例子。我有同樣的效果。

出了什麼問題?我知道有類似的主題,但我似乎無法找到與我的相匹配的主題。謝謝你的幫助。

問候 拉法爾

回答

1

你是因爲你的JavaScript代碼

<p id="hello"> 

定義的元素之前運行得到一個問題。

最簡單的解決方案是將腳本包含在正文部分的末尾而不是頭部分,但這會導致document.write調用在其餘內容之後發生。

另一種解決方案是將代碼放在裏面兩個函數這樣

function do_conversion() { 
    var inches = 12; 
    var meters = inchestometers(inches); 
    document.write("the value in meters is " + meters); 
} 
function say_hello() { 
    var hello = document.getElementById("hello"); 
    hello.firstChild.nodeValue = "Hello World"; 
} 

然後改變身體部分這樣

<body onload='say_hello()'> 
    <script> 
     do_conversion(); 
    </script> 

    <p id="hello">Hello</p> 

</body> 
+0

確定,但也有一些教程,告知,我們應該把在我的公司asp.net腳本被加載到圓頂之前,是否可能加載的sciprs是在page_load事件? – 2013-04-29 18:17:48

+0

將腳本放置在頭部或身體末端都是常規操作。還有些時候,可以通過將其作爲事件處理程序添加或在文檔加載時使用document.write()插入內容,從而在正文中調用腳本是合理的。有些人主張在身體裏沒有任何腳本,並且在onload事件處理程序中執行所有的dom操作和插入動態ciontent,但是我認爲這取決於你在做什麼以及最終用戶是誰 – 2013-04-30 10:17:30

+0

也檢查了這個問題http: //stackoverflow.com/questions/436411/where-is-the-best-place-to-put-script-tags-in-html-markup – 2013-04-30 10:17:57

相關問題