简体   繁体   中英

W3 validate html error with 1 line of javascript code

I get the following error with validator.W3.org

Line 70, Column 26: character "<" is the first character of a delimiter but occurred as data

if (remainingSeconds < 10) {

Line 70, Column 26: StartTag: invalid element name

if (remainingSeconds < 10) {

This is the code I use.

<script type="text/javascript">
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
    remainingSeconds = "0" + remainingSeconds;  
}
</script>

If I delete the < or change the < to a = then the error is gone.

Anybody an idea?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

You're validating an XHTML document, so you have to use CDATA markers around your script contents .

<script>
  <![CDATA[
  // JavaScript goes here
  ]]>
</script>

Personally I don't know why you'd use XHTML in this day and age, but whatever.

If you are validating as XHTML, try wrapping your JavaScript in <![CDATA[]]> blocks:

What does <![CDATA[]]> in XML mean?

You're using strict XHTML, so all characters that are part of the XML syntax (pretty much) have to be escaped properly if you want to use them as text. In XHTML, the usual way to do that is with a CDATA block that's escaped in a way to be compatible with HTML:

<script type="text/javascript">//<![CDATA[
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
    remainingSeconds = "0" + remainingSeconds;  
}
//]]></script>

However, there are two better fixes:

  • Use HTML5 ( <!DOCTYPE html> ), not XHTML
  • Use an external script, <script type="text/javascript" src="second-passed.js"></script>

Both are better practice.

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