简体   繁体   中英

JavaScript validation problems

In the following code document.write("<h1>" + Date() + "<\\/h1>"); I need to use \\ in the closing h1 tag to validate my HTML page. Whats the purpose of using \\ in the tag.

The backslash character is usually used to escape "special" characters. You shouldn't need it in there.

You shouldn't be writing DOM elements using document.write , this overwrites any existing DOM elements that were in the HTML document.

The second slash (backslash) that you've used shouldn't be needed. Take a look at this example for both of my points:

http://jsfiddle.net/SrQKt/7/

In JavaScript, only /script needs to be escaped \\/script

In HTML validation move the JS to an external file to allow validation.

Using innerHTML is sligthly better - DOM manipulation will also do the job inline or in external files:

var header = document.createElement("h1");
header.appendChild(document.createTextNode(new Date()))
someContainer.appendChild(header);

for example

There is no formal error in your JavaScript code. The problem is probably that you have it inside an HTML document, in a script element, and then </h1> may become a problem (depending on HTML version and software used). At the HTML level, the \\ breaks the construct so that it won't be parsed as an end tag. In a JavaScript literal, \\/ means just the same as / (you can “escape” a normal character, too).

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