2015-11-07 47 views
0

我需要在帶有字符串html標籤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>。 我該怎麼做?

謝謝!

回答

2

如果HTML編碼您的字符串,這樣像<符號成爲&lt,它會工作。

document.write("&lt;h1&gt;");將打印<h1>

順便說一句,jQuery`s text()函數可以實現這個要求。

function escapeHtml(unsafe) { 
    return unsafe 
     .replace(/&/g, "&amp;") 
     .replace(/</g, "&lt;") 
     .replace(/>/g, "&gt;") 
     .replace(/"/g, "&quot;") 
     .replace(/'/g, "&#039;"); 
} 

document.write(escapeHtml("<h1>title<u> number</u> 1</h1>")); 

這將打印<h1>title<u> number</u> 1</h1>。從this question採取

功能。致信@bjornd。

+0

嗯,但我需要更通用的東西,因爲H1只是一個例子。該字符串可能由任何html標籤組成。 – lonely

+0

您只需創建一個函數來替換您的所有標籤。我會添加一個例子 – victor

1

轉換所有HTML字符實體,可能的話,像這樣:

str = str.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;'); 

順序並不重要,除了更換符號必須先否則會造成奇怪的行爲。

+0

感謝您的回覆,但我得到這個錯誤:'Uncaught TypeError:toPrint.replace不是函數'.. – lonely

+0

給我從控制檯輸入「typeOf toPrint」的結果 – Quantum

+0

實際上,在執行之前將toPrint轉換爲字符串替換。 – Quantum