我不知道这是否发生了,但是如果您的站点告诉浏览器它是严格的 XHTML,那么它将无法工作document.write
。document.writeln
我相信要发生这种情况,您必须使用严格的 DOCTYPE 并将Content-Type
标头设置为application/xml+xhtml
而不是text/html
(许多服务器下的默认值)。这是因为以这种方式操作 DOM 可能会破坏它。例如,如果我将以下内容放在经过验证的网页的中途:
<script type="text/javascript">
<!--
document.write("</body>");
// -->
</script>
该文档将验证并符合 XHTML,但不能在大多数浏览器中工作。
另一种方法是创建一个 DOM 节点,应该在其中插入电子邮件地址,并在页面加载时插入它。例如:
<p>My email address is <span id="email"></span>.</p>
<script type="text/javascript">
<!--
document.body.onload = function() {
document.getElementById("email").textContent = String.fromCharCode(60,97,32,104,114,101,102,61,34,109,97,105,108,116,111,58,119,101,98,109,105,110,64,97,116,101,110,118,101,108,100,116,46,111,114,103,34,62,119,101,98,109,105,110,64,97,116,101,110,118,101,108,100,116,46,111,114,103,60,47,97,62);
};
// -->
</script>
或者,当您设置了 jQuery 时:
<p>My email address is <span id="email"></span>.</p>
<script type="text/javascript">
<!--
$( function() {
$("#email").text(String.fromCharCode(60,97,32,104,114,101,102,61,34,109,97,105,108,116,111,58,119,101,98,109,105,110,64,97,116,101,110,118,101,108,100,116,46,111,114,103,34,62,119,101,98,109,105,110,64,97,116,101,110,118,101,108,100,116,46,111,114,103,60,47,97,62));
} );
// -->
</script>