我在javascript中遇到CDATA问题

I am having issues with CDATA in javascript

本文关键字:CDATA 问题 遇到 javascript 我在      更新时间:2023-09-26

我是javascript的新手,我做过C++C#VB。但这本javascript书很难理解,它只是练习,没有完整的代码可看。无论如何,我正在做一个简单的项目,但我不明白哪里出了问题。CDATA是我认为我出错的地方。这是我的第二个项目,第一个很容易,直到CDATA和Var,我才被卡住。我知道这段代码已经过时了,但我正在按照这本书学习基本的JS,并努力向上。这是代码:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Largest Islands</title>
<meta http-equiv="content-type" content="text/html; charset=iso-
8859-1" />
</head>
<body>
<h1>Largest Islands</h1>
<script type="text/javascript">
/* <![CDATA[ */
var island1Name = "Greenland";
var island2Name = "New Guinea";
var island3Name = "Borneo";
var island4Name = "Madagascar";
var island5Name = "Baffin";
var island1Size = 2175600;
var island2Size = 790000;
var island3Size = 737000;
var island4Size = 587000;
var island5Size = 507000;
document.write("<p>The largest island
in the world is " + island1Name
+ " with " + island1Size + " miles.</p>");
document.write("<p>The second largest island
in the world is " + island2Name
+ " with " + island2Size + " miles.</p>");
document.write("<p>The third largest island
in the world is " + island3Name
+ " with " + island3Size + " miles.</p>");
document.write("<p>The fourth largest island
in the world is " + island4Name
+ " with " + island4Size + " miles.</p>");
document.write("<p>The fifth largest island
in the world is " + island5Name
+ " with " + island5Size + " miles.</p>");
/* ]]> */
</script>
</body>
</html>

这是一个非常简单的项目,我只需要一些帮助来弄清楚我哪里出了问题。提前感谢

我认为您的问题是这里的换行符。您的代码:

document.write("<p>The largest island
in the world is " + island1Name
+ " with " + island1Size + " miles.</p>");

应为:

document.write("<p>The largest island in the world is " + island1Name
+ " with " + island1Size + " miles.</p>");

如果你在一行中开始一个字符串,但你没有在同一行结束,这将导致换行引发错误。此外,我建议您使用firefox和firebug进行开发,在那里您可以调试脚本。

在本地运行时,JavaScript错误控制台会非常清楚地显示问题所在。它甚至会给您行号。

document.write("<p>The largest island
in the world is " + island1Name...

在JavaScript字符串的中间不能有换行符。

document.write("<p>The largest island in the world is " + island1Name...

工作。您需要修复所有这些问题,并开始在每个主要浏览器中使用可用的开发工具。

我认为问题来自于破坏字符串

代替

document.write("<p>The largest island
in the world is " + island1Name

尝试

document.write("<p>The largest island" 
+ "in the world is " + island1Name

您的问题是在JavaScript:中不允许有这样的多行字符串

document.write("<p>The second largest island
in the world is " + island2Name

如果你在错误的地方去掉了这些新行,代码就可以工作了。这条线现在看起来是这样的:

document.write("<p>The second largest island in the world is " + island2Name

示例:http://jsbin.com/igowel/1/edit

要继续使用JavaScript,请习惯使用控制台和开发人员工具。对于Chrome,看看这个问答;A: 如何在Google Chrome中使用JavaScript控制台?