当文本显示在broswer页面上时,字符得到逃脱

characters getting un-escapped when the text is shown on the broswer page

本文关键字:字符 逃脱 显示 文本 broswer      更新时间:2023-09-26

有一些从服务器获取的内容显示在浏览器的新页面上。例如,内容为

"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"

为什么会发生这种情况?我需要按原样显示字符串。我应该做什么改变来实现这个目标?我需要保留这些转义字符。

文档。writeln期望它的输入是HTML,所以你的内容被视为这样,这包括转换实体引用,如&amp;&lt;&<。毕竟,您希望将<title>视为标记而不是某些<符号,对吗?

有很多方法可以解决你的问题。您可以做的一种可能性是使用DOM方法在单独的传递中插入文本内容。这样你就不必处理html转义问题了。

top.consoleRef.document.close();
var doc = top.consoleRef.document;
var textarea = doc.getElementsByTagName('textarea')[0];
textarea.value = "Apple &amp; Orange";

或者,您可以html转义内容字符串以将其转换为"Apple &amp;amp; Orange",这就是在原始html文档中编写"Apple &amp; Orange"的方式。