简体   繁体   English

JavaScript验证问题

[英]JavaScript validation problems

In the following code document.write("<h1>" + Date() + "<\\/h1>"); 在下面的代码document.write("<h1>" + Date() + "<\\/h1>"); I need to use \\ in the closing h1 tag to validate my HTML page. 我需要在结束的h1标签中使用\\来验证我的HTML页面。 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. 您不应该使用document.write编写DOM元素,这会覆盖HTML文档中所有现有的DOM元素。

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/ http://jsfiddle.net/SrQKt/7/

In JavaScript, only /script needs to be escaped \\/script 在JavaScript中,仅/script需转义\\/script

In HTML validation move the JS to an external file to allow validation. 在HTML验证中,将JS移至外部文件以进行验证。

Using innerHTML is sligthly better - DOM manipulation will also do the job inline or in external files: 使用innerHTML更好-DOM操作也可以内联或在外部文件中完成工作:

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. 您的JavaScript代码中没有形式错误。 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). 问题可能是您将它放在HTML文档中的script元素中,然后</h1>可能会成为问题(取决于HTML版本和所使用的软件)。 At the HTML level, the \\ breaks the construct so that it won't be parsed as an end tag. 在HTML级别上, \\破坏了构造,因此不会将其解析为结束标记。 In a JavaScript literal, \\/ means just the same as / (you can “escape” a normal character, too). 在JavaScript文字中, \\/含义与/相同(您也可以“转义”一个普通字符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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