为什么我的脚本未通过 w3c 验证?
我有这段代码:
<script language="javascript" type="text/jscript">
document.write("<img src='http://dm.leadgenesys.com/jpgp.lgt?en=P.........TP_Q=&ur=' + escape(document.referrer) + '' border='0' alt='no alt' />");
</script>
并且...当我尝试验证它时,出现以下错误:
文档类型不允许元素 此处为“img”
…rer) + '" border="0" alt="无 alt" >>');
上面指定的元素是在 不允许的上下文。 这 可能意味着你错误地 嵌套元素——例如“样式” 改为“body”部分中的元素 内部“头部”——或两个元素 重叠(这是不允许的)。
知道我可以做些什么来使这个 JavaScript w3c 兼容吗?
I have this piece of code:
<script language="javascript" type="text/jscript">
document.write("<img src='http://dm.leadgenesys.com/jpgp.lgt?en=P.........TP_Q=&ur=' + escape(document.referrer) + '' border='0' alt='no alt' />");
</script>
and... when I try to validate it, I'm given this error:
document type does not allow element
"img" here…rer) + '" border="0" alt="no alt"
/>');The element named above was found in a
context where it is not allowed. This
could mean that you have incorrectly
nested elements -- such as a "style"
element in the "body" section instead
of inside "head" -- or two elements
that overlap (which is not allowed).
Any idea what I can do to make this JavaScript w3c compliant?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
很简单:不要尝试将 JavaScript 验证为 HTML。
您可以通过多种方式执行此操作...但到目前为止最好的方法是将其移至单独的 JS 文件中,然后从简短的脚本中调用它
...或者更好的是,放弃
document。 write()
完全并在加载后操作 DOM。另请参阅:不引人注目的 JavaScript
Simple: don't try to validate your JavaScript as HTML.
You can do this in a number of ways... But the best by far is to move it out into a separate JS file, and then either call it from a short script
...or better yet, ditch
document.write()
entirely and manipulate the DOM after it has loaded.See also: Unobtrusive JavaScript
另一种让验证器保持沉默的方法...
这样说:
CDATA 部分对于验证器来说应该足够了, /* 样式注释 */ 适用于无法识别 CDATA 标签的旧浏览器(否则会破坏 javascript) 。
Another way to silence the validator...
Put it like this:
The CDATA part should be enough for the validator, the /* style comments */ are for older browsers which do not recognize the CDATA tag (it would otherwise break the javascript).
怎么样?
看看“脚本”的内容在“html注释”里面
How aboout
See that the content of the "script" is inside "html comments"?
您的
中可能有
元素,因此本质上您正在尝试创建一个
在你的文档的头部,这是行不通的。 您需要将脚本放入
中。
但是,我建议您通过 DOM 添加元素,因为您'遇到此类问题的可能性就会降低。
You probably have your
<script>
element in your<head>
, so essentially you're trying to create an<img>
in the head of your document, which doesn't work. You need to put the script in the<body>
.However, I'd recommend you add the element via the DOM instead, because you'll be less likely to run into these kinds of problems.
它是 HTML4 标准的一部分。 您必须转义 SCRIPT 标记内发现的“
另一种可能更好的解决方案是将 JS 代码移动到外部文件中。
参考
It's part of the HTML4 standard. You must escape "</" sequences found inside SCRIPT tags.
Another solution, and probably better, is to move the JS code in external files.
Reference
或者:
Or: