簡體   English   中英

如何使用 javascript 打印孔 HTML 標簽。 喜歡如何打印 thi 孔線(<a href="link">文本</a>),而不僅僅是作為鏈接的文本

[英]How can I print hole HTML tag using javascript. like how to print thi hole line (<a href="link">text</a>) instead of just text as a link

當我看到這個例子時,它使用getElementsByTagName()方法來帶入所有錨標記,然后使用索引 [0] 將第一個元素帶入這個 HTMLCollection。 將其分配給 x 變量。 如果我console.log(x)我將得到我的 HTML DOM 中的第一個錨標記。 但是如果我使用innerHTML將此 X 分配給一個段落,結果將顯示錨點內的 href 值,我希望將整個錨點標記添加為 HTML 元素並在段落內顯示它的內容,即本例中的內容你好世界'。 任何解釋為什么會這樣? 謝謝你。

 const x = document.getElementsByTagName('a')[0]; console.log(x); // will print out the anchor tag element document.getElementById('demo').innerHTML = x; // will add the href attribute value of the anchor only, But I expected that I will get the text 'hello world'
 <!DOCTYPE html> <html> <body> <a href="https://www.w3schools.com/html/">hello world</a> <a href="https://www.w3schools.com/css/">Welcome</a> <p id="demo"></p> </body> </html>

當您將x分配給innerHTML時,它會轉換為字符串。 將 DOM 元素轉換為字符串不會返回元素的完整 HTML; 在大多數情況下,它會返回一個類似[object HTMLDivElement]的字符串,但錨會覆蓋它並返回href值(請參閱HTMLAnchorElement.toString()

要獲取元素的完整 HTML,可以使用outerHTML屬性。

 const x = document.getElementsByTagName('a')[0]; console.log(x); // will print out the anchor tag element document.getElementById('demo').innerHTML = x.outerHTML; // will add the href attribute value of the anchor only, But I expected that I will get the text 'hello world'
 <!DOCTYPE html> <html> <body> <a href="https://www.w3schools.com/html/">hello world</a> <a href="https://www.w3schools.com/css/">Welcome</a> <p id="demo"></p> </body> </html>

  • innerHTML 接受字符串輸入,並將HTML tag轉換為有效標記並保持內容不變。 所以,這里<a>標簽被轉換成一個標簽,你不能打印孔<a href="link">text<a/a>它只是打印文本作為錨標簽。 欲了解更多信息,請訪問 此頁面

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM