2011-10-03 127 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),你看到这个错误覆盖一切你有很多错别字和不正确的变量名(例如,你已经定义了变量,但在引用它们时使用了不同的名称) - 纠正它们,你的代码将运行。