javascript - document.write XHTML 1.0 过渡验证错误

标签 javascript validation xhtml-transitional

作为我的作业任务的一部分,我需要使用 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/

相关文章:

javascript - AngularJS - ng-keypress 不适用于输入事件

javascript - 如何解析 JS Date 在所有浏览器中保持一致

java - 如何检查用户输入的日期是否大于java中当前日期的32天

ruby-on-rails - 仅在更新时验证

jquery - 改造旧的 XHTML 网站以适应移动设备?

javascript - XHTML Transition 中的 iframe 不起作用

javascript - 将项目添加到收藏夹并将其保存在 Cookie 中

javascript - 在 Vue.js 应用程序中初始化 firebase 3.4.0

javascript - 类型错误 : Cannot read property 'getMonth' of undefined

css - 3 个固定列(页眉和页脚)使用 DIV,没有绝对 DIV,IE 友好,所有列均等拉伸(stretch)