作为我的作业任务的一部分,我需要使用 XHTML 1.0 Transitional 显示确认()和提示()函数的简单用法。所有代码都需要验证。
当我尝试验证代码时,我收到以下错误:
第 12 行,第 24 列:文档类型不允许此处使用元素“p”
<!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>
<title>java script demonstration</title>
</head>
<body>
<script type="text/javascript">
var response=confirm("This box was created using Javascript - Click on OK to continue")
if (response)
{document.write("<p>You have just clicked on OK</p>")}
else
{document.write("You have just clicked on Cancel")}
var reply=prompt("Please enter your Name")
document.write("your name is " + reply +"")
</script>
</body>
</html>
是否可以将 p 元素合并到代码中,同时仍然通过验证器?
最佳答案
因为您使用的是 XHTML,所以您需要将 JavaScript 包装在 CDATA 中:
<!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>
<title>java script demonstration</title>
</head>
<body>
<script type="text/javascript">
//<![CDATA[
var response=confirm("This box was created using Javascript - Click on OK to continue")
if (response)
{document.write("<p>You have just clicked on OK</p>")}
else
{document.write("You have just clicked on Cancel")}
var reply=prompt("Please enter your Name")
document.write("your name is " + reply +"")
//]]>
</script>
</body>
</html>
这只是告诉编译器 CDATA 标记中包含的内容是数据而不是标记的一种方式。如果您计划执行任何内联 JS,这是必要的。
关于javascript - document.write XHTML 1.0 过渡验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27336005/