0

浏览器说我的 javascript 在我的 xhtml 中的这个函数中存在错误。如果我删除此功能,错误就会消失。对我来说,这段代码在语法上看起来很完美:

    function toAscii(text) {
        for (var i=0; i<text.length; i++) {
            var charCode = text.charCodeAt(i);
            var ascii = charCode.toString(2);
            console.log(ascii);
        }
    }       

铬错误:

This page contains the following errors:

error on line 19 at column 31: error parsing attribute name
Below is a rendering of the page up to the first error.

火狐错误:

Erro no processamento de XML: formatação incorreta 
Posição: file:///C:/Users/Carlos/Desktop/ascii%20converter.xhtml
Número da linha 19, coluna 33:
                        for (var i=0; i<text.length; i++) { 
---------------------------------------------------^

这是整个 XHTML:

<?xml version="1.0" encoding="UTF-8"?>
<!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>ASCII Converter</title>
    <meta charset="UTF-8"/>

    <script type="text/javascript">
        function converter() {
            var text = document.getElementById('texto').value;
            toAscii(text);
        }

        function toAscii(text) {
            for (var i=0; i<text.length; i++) {
                var charCode = text.charCodeAt(i);
                var ascii = charCode.toString(2);
                console.log(ascii);
            }
        }       
    </script>
</head>

<body>
    Texto (Entrada):<br/>
    <input id="texto" type="text"/><br/>
    ASCII (Saída):<br/>
    <input id="ascii" type="text"/><br/>
    <input type="button" id="botao" value="Converter" onclick="converter()"/><br/>  
</body>

</html>
4

2 回答 2

3

由于您使用的是 xhtml 并且代码中有 a <,因此您必须将代码包含在 cdata 块中

<script type="text/javascript"><![CDATA[
    function converter() {
        var text = document.getElementById('texto').value;
        toAscii(text);
    }

    function toAscii(text) {
        for (var i=0; i<text.length; i++) {
            var charCode = text.charCodeAt(i);
            var ascii = charCode.toString(2);
            console.log(ascii);
        }
    }       
]]></script>
于 2013-10-20T01:56:47.483 回答
3

严格来说,XHT​​ML 不允许像使用 HTML 那样将 javascript 卡在标题中。正如有人提到的,它应该包含在 CDATA 部分中。作为旁注,您发布的代码在我的浏览器上运行,但它可能是宽松的。查看此参考以获取有关 xhtml 和嵌入式 css/javascript 的更多信息:

https://developer.mozilla.org/en-US/docs/Properly_Using_CSS_and_JavaScript_in_XHTML_Documents

于 2013-10-20T01:58:15.603 回答