我需要在新窗口中打印字符串 html 标签 html。 我所做的是:
function printNewTab(toPrint, title) {
var newWin = window.open("about:blank");
newWin.document.write("<html><head><title>" + title + "</title></head></html>");
newWin.document.write(toPrint.toString());
console.log(title + ":");
console.log(toPrint);
}
但是如果我有一个像这样的字符串:
var s = "<h1>title<u> number</u> 1</h1>";
并使用上面的方法:
printNewTab(s, "title");
我获得一个新窗口,其中文本不显示标签,但采用 html 格式。
虽然我真的很想看到打印的 <h1>title<u> number</u> 1</h1>
。
我怎样才能做到这一点?
谢谢!
最佳答案
如果您对字符串进行 html 编码,则像 <
这样的符号成为<
,它会起作用的。
document.write("<h1>");
将打印<h1>
.
顺便说一句,jQuery 的 text() 函数可以为您完成此操作。
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
document.write(escapeHtml("<h1>title<u> number</u> 1</h1>"));
这将打印 <h1>title<u> number</u> 1</h1>
.
函数取自this question 。感谢@bjornd。
关于javascript - 在新窗口中打印带有标签的html文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33589137/