从服务器获取一些内容并显示在浏览器的新页面上。例如内容是
"Apple & Orange"
但是当它在网页代码中呈现时
function writeConsole(content,idx) {
top.consoleRef=window.open('','myconsole' + idx,
',menubar=0'
+',toolbar=1'
+',status=0'
+',scrollbars=1'
+',resizable=1');
top.consoleRef.document.writeln(
'<html><head><title> Generated Content </title></head>'
+'<body bgcolor=white onLoad="self.focus()">'
+ '<textarea rows="500" cols="500">'
+ content
+ '</textarea>'
+'</body></html>'
);
top.consoleRef.document.close();
}
它被渲染为
"Apple & Orange"
为什么会发生这种情况?我需要显示字符串。为了实现这一目标,我应该做出哪些改变?我需要保持这些转义字符不变。如有任何帮助或建议,我们将不胜感激。
最佳答案
document.writeln 期望其输入为 HTML,因此您的内容将被视为 HTML,这包括转换实体引用,例如 &
或<
进入&
和<
。毕竟,您想要<title>
被视为标签而不是某些 <
符号,对吗?
有多种方法可以解决您的问题。您可以做的一种可能是使用 DOM 方法将文本内容插入到单独的 channel 中。这样您就不必处理 html 转义问题。
top.consoleRef.document.close();
var doc = top.consoleRef.document;
var textarea = doc.getElementsByTagName('textarea')[0];
textarea.value = "Apple & Orange";
或者,您可以html escape内容字符串将其转换为 "Apple &amp; Orange"
,这就是你可以写 "Apple & Orange"
在原始 html 文档中。
关于javascript - 当文本显示在浏览器页面上时,字符未转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25123722/