2011-10-03 123 views
-3

我是新來的JavaScript和試圖執行下面的代碼,誰能告訴我爲什麼只有第一個document.write正在執行,而不是其他人。java腳本錯誤與document.write()

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 
<title>my first java script</title> 
</head> 
<body> 
<script type="text/javascript"> 
var myhello="hello world, welcome to java script"; 
var heading="a page of java script"; 
var linktag="<a href=\"http://www.google.com\">wanna search on google</a>"; 
var redtext="<span style=\"color:red\">I am so colorful today!</span>"; 
var begineffect="<strong>"; 
var endeffect="</strong>"; 
var beginpara="<p>"; 
var endpara="</p>"; 
document.write(begineffect+heading+endeffect); 
document.write(begingpara); 
document.write(hello); 
document.write(endpara); 
document.write(begingpara); 
document.write(linktag); 
document.write(endpara); 
document.write(beginpara); 
document.write(redtext); 
document.write(endpara); 
</script> 
</body> 
</html> 

我在所有網頁瀏覽器中測試了以下代碼。

+3

你說你是javascript新手,所以我會給你一個小提醒。不要使用document.write()。閱讀更多關於爲什麼在這裏http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – timrwood

回答

5

它產生一個錯誤,因爲你沒有一個變量,名爲hello

var hello = 'define something here'; 
document.write(hello); 

使用很好的瀏覽器如Chrome,或者如果您使用Web檢查火狐+螢火蟲,就會發現這樣的錯誤。

Uncaught ReferenceError: begingpara is not defined 

http://www.google.com/chrome/intl/en/webmasters-faq.html#jsexec

-1

它讓別人不再存在

+0

這隻會發生如果'document.write'在頁面加載後調用。 – Dennis

+0

非常真實。看起來我沒有仔細閱讀代碼 – yoozer8

4

如果您檢查您的控制檯(F12在Chrome或負載Firebug爲Firefox),你看到這個錯誤覆蓋一切你有很多錯別字和不正確的變量名(例如,你已經定義了變量,但在引用它們時使用了不同的名稱) - 糾正它們,你的代碼將運行。