简体   繁体   中英

JavaScript not working in XHTML

I am trying to make an XHTML page with JavaScript. JavaScript does not work.

I have written the simplest file, but I can not find an error. To me it seems fine. Please, give me some advice.

    <!DOCTYPE html>
    <html   version="-//W3C//DTD XHTML 1.1//EN"
            xmlns="http://www.w3.org/1999/xhtml"
            xml:lang="en"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://www.w3.org/1999/xhtml
                                http://www.w3.org/MarkUp/SCHEMA/xhtml11.xsd">
    <head>
        <title>XHTML Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta charset="utf-8" />
        <meta name="description" content="XHTML Test" />
        <meta name="keywords" content="XHTML, Test" />
        <link rel="stylesheet" type="text/css" href="a.css" />
        <script type="application/javascript" charset="utf-8" src="a.js" defer="defer"></script>
        <script type="application/javascript">
            function init()
            {
                alert('x');
            }
        </script>
    </head>
    <body onLoad="init();">
    <div id="main" class="c1">
        XHTML Test.
    </div>
    </body>
    </html>

I have tried an external JS file and inline script inside <script> . Neither works for me.

The document is saved as index.xhtml and served by Apache as it should: Content-Type: "application/xhtml+xml"

If I rename the file as index.html it is served as HTML and the script works. I need it to be XHTML.

Thank you.

XHTML has case-sensitive tag and attribute names. They must all be lower case.

You have written onLoad instead of onload .

in xhtml you need to use CDATA to tell the browser your script is just text not xml

<script type="application/javascript">
//<![CDATA[
    function init()
    {
        alert('x');
    }
//]]>
</script>

edit:

try: <body onload="init();">

based on: https://www.w3.org/TR/xhtml1/#h-4.11

4.11. Attributes with pre-defined value sets

HTML 4 and XHTML both have some attributes that have pre-defined and limited sets of values (eg the type attribute of the input element). In SGML and XML, these are called enumerated attributes. Under HTML 4, the interpretation of these values was case-insensitive, so a value of TEXT was equivalent to a value of text. Under XML, the interpretation of these values is case-sensitive, and in XHTML 1 all of these values are defined in lower-case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM