简体   繁体   English

在 html 内容中显示 html 标签,在 html 中显示 html 代码片段

[英]show html tags in html content, show html code snippet in html

I was wondering if there is a way I could apply htmlentities() to var x so that if I put <p>hello</p> into the text area and press the button it would display <p>hello</p> instead of hello using the below code.我想知道是否有一种方法可以将htmlentities()应用于var x以便如果我将<p>hello</p>放入text area并按下按钮,它将显示<p>hello</p>使用下面的代码你好

Thanks in advance提前致谢

 function myFunction1() { var x = document.getElementById("myText1").value; document.getElementById("demo1").innerHTML = x; }
 <textarea name="myText" id="myText1" type="text"></textarea> <button onclick="myFunction1()">thing</button> <p><span id="demo1"></span></p>

You need to use <xmp> tag您需要使用<xmp>标签

 <xmp> <p>hello</p> </xmp>

 function myFunction1() { var x = document.getElementById("myText1").value; document.getElementById("demo1").innerHTML = x; }
 <textarea name="myText" id="myText1" type="text"></textarea> <button onclick="myFunction1()">Show</button> <p><xmp id="demo1"></xmp></p>

Generally this is done by replacing the < symbol with the "less than" HTML encoding ( &lt; ), and > with "greater than" ( &gt; ).通常,这是通过将<符号替换为“小于”HTML 编码 ( &lt; ),并将>替换为“大于”( &gt; ) 来完成的。

For instance, you should use basic string methods to replace something like例如,您应该使用基本的字符串方法来替换类似

"<p>hello</p>"

with

"&lt;p&gt;hello&lt;/p&gt;"

(Otherwise, adding it to an element's innerHTML will read it as HTML, including the tags.) (否则,将其添加到元素的 innerHTML 会将其读取为 HTML,包括标签。)

I should point out that you can also try just wrapping everything in the <pre> tag, but I've had varying results with it.我应该指出,您也可以尝试将所有内容都包装在<pre>标签中,但我已经得到了不同的结果。 I think the method above is a safer bet.我认为上面的方法是一个更安全的赌注。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM